In Ruby, if is an expression, not a statement, thus it returns a value. This may not seem useful at first glance, but it lends itself to forming neat, concise code… Like most things in Ruby, actually.

Setting Values Concisely

Say you want to define a variable differently based on the result of an if expression. If you’re not a native to Ruby, you may find yourself coding something like this:

1
2
3
4
5
if name == 'Susie'
  age = 12
else
  age = 14
end

This breaks from the DRY principle because age = is repeated in each case. Since if is an expression, however, you could write something like this:

1
2
3
4
5
age = if name == 'susie'
  12
else
  14
end

This evaluates the condition name == 'susie' and if it’s true, dumps the value 12 into age; oppositely, if it’s false, it dumps the value 14 into age. To be even more succinct about it, try:

1
age = name == 'susie' ? 12 : 14

One-Line if’s

A lot of the time it may be necessary to write out a one-line block of code within an if. There are several ways to do this without being as verbose as

1
2
3
if expression
  action
end

Three lines! How wasteful. Instead, try one of the following:

  • if expression then action or more concisely:
  • if expression: action or my personal favorite:
  • action if expression or for the C fan:
  • expression ? if result is true : if result is false

For a negated if, i.e., if !expression, it may make more sense to you to use unless:

1
2
3
unless expression
  action
end

You can use unless in the same way that you use if: all the one-liners above will work. Note, however, that elsif is not available with an unless expression, though else is.

Doubling Up

You can have expressions all over the place, following and preceding blocks. For example:

1
2
3
while condition
  action
end if expression

That while loop will only get executed if expression is true. This may not be the most readable chunk of code, however, since the while is a multi-line block. However, if and unless expressions following one-line blocks are handy.