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:
number = 5if number.odd?puts "The number is odd."end
We can also write this:
number = 5puts "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:
number = 6unless number.odd?puts "The number is not odd."endputs "The number is not odd." unless number.odd?