Conditionals Return Values
Learn how conditional statements return values and how that can be useful.
We'll cover the following...
Another extremely useful aspect about if
and unless
statements in Ruby is that they return values.
An if
statement, with all of its branches, evaluates the value returned by the statement that was last evaluated, just like a method does.
Example
For example, take a look at this:
Press + to interact
number = 5if number.even?puts "The number is even"elseputs "The number is odd"end
We can also assign the return value of the if
statement to a variable, and
then output it:
Press + to interact
number = 5message = if number.even?"The number is even"else"The number is odd"endputs message
Also, for the same reason, if we define a method that contains nothing but a single if
/else
statement, the method again returns the last statement evaluated:
Press + to interact
def message(number)if number.even?"The number is even"else"The number is odd"endendputs message(2)puts message(3)
The first method call, message(2)
, outputs The number is even
, and the second, message(3)
, outputs The number is odd
.
to save progress
Shorthand Syntax
Nothingness and the Truth
to save progress