Search⌘ K

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:

Ruby
number = 5
if number.even?
puts "The number is even"
else
puts "The number is odd"
end

We can also assign the return value of the if statement to a variable, and then output it:

Ruby
number = 5
message = if number.even?
"The number is even"
else
"The number is odd"
end
puts 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:

Ruby
def message(number)
if number.even?
"The number is even"
else
"The number is odd"
end
end
puts 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.