Shorthand Syntax

Learn about other ways to write conditional statements.

We'll cover the following

A trailing if

One particularly nice feature in Ruby is that we can append the if statement to the code on the if branch if it’s just a single line. So instead of this:

Press + to interact
number = 5
if number.odd?
puts "The number is odd."
end

We can also write this:

Press + to interact
number = 5
puts "The number is odd." if number.odd?

This not only saves us two lines, but it also reads great!

The unless statement

In addition to if, Ruby also knows a statement called unless that’s used when we want to do something if the condition doesn’t apply (doesn’t evaluate to true). Again, we can also append the unless statement to the end of the line, so these two are the same:

Press + to interact
number = 6
unless number.odd?
puts "The number is not odd."
end
puts "The number is not odd." unless number.odd?