Conditionals Return Values
Explore how Ruby conditionals like if and unless return values based on their last evaluated expression. Learn to assign these values to variables and how methods with conditionals return results, enhancing your coding flexibility and understanding of Ruby's flow control.
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:
We can also assign the return value of the if statement to a variable, and
then output it:
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:
The first method call, message(2), outputs The number is even, and the second, message(3), outputs The number is odd.