Wednesday, August 10, 2011

The Beauty of ||

The || operator is one of those things that makes Ruby such a sweet language to write code in. When used with multiple expressions, it will return the first non-false value.
true || false
#=> true

false || true
#=> true

nil || 1
#=> 1

false || 'hi'
#=> "hi"

false || nil || "whatever"
#=> "whatever"

false || "look at me" || "ignored"
#=> "look at me"

If there aren't any non-false values, the last value will get returned.
false || nil
#=> nil

nil || false
#=> false

When it finds a non-false value, it is "returned" and none of the other statements are evaluated
false || (p "hi")
# "hi"
#=> "hi"

true || (p "hi")
#=> true

Built in assignment with ||=

A close sibling to the || operator is the ||= operator. It behaves the same way, but also assigns the value to a variable. This is useful for default value assignment.
val ||= "some value"
#=> "some value"
val ||= "another value"
#=> "some value"
In the line 1, val is nil so it gets assigned to the string "some value". In line 3, val already has a non-false value, so an ||= assignment to "another value" is ignored.

Using || with rescue

Occasionally I need to perform a risky move that could throw an exception. If an exception is thrown, then I simply want a default value returned. The || operator comes in handy there.
raise "some exception" rescue nil || "saved"
#=> "saved"
This example is completely impractical, but it illustrates the point quite nicely.

No comments:

Post a Comment