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:
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:
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:
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
if expression
action
end
Three lines! How wasteful. Instead, try one of the following:
if expression then actionor more concisely:
if expression: actionor my personal favorite:
action if expressionor 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:
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:
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.
2 Comments
In PHP:
age = (name == “Susie”) ? 12 : 14;
That is not easily parsed by a human reader. Code must be maintained, so it is important to make it easy on the maintainer rather than the machine parser.
Well it is useful for extension loading in PHP (and in fact, it’s the only thing I use that type of if statement in, for example:
$prefix = (PHP_SHLIB_SUFFIX == "dll") ? "php_" : '';
it’s a lot neater than a full-blown if statement, and I understand what it’s for (I have no clue why the extensions have to have ‘php_’ prefixed before them on Windows, but not on any other OS), since it’s the only situation I use it for…
And you do get used to associating that with an if statement if you see it often enough, and if you wrote it, you should reasonably be expected to know what it means and does when you’re maintaining it, right?