Ruby’s conditional syntax is ‘truthy’, meaning that any statement in a conditional that evaluates to
nil is considered to be equivalent to
false and anything not-
nil can be considered to be
…overcomplicating your conditions.
# Example 1 unless something.nil? # do something end # Example 2 if !something.nil? # do something end # Example 3 if !!something # do something end
# Instead of Examples 1,2 & 3 if something # do something end
#nil? check as part of a statement in a negative conditional, as in the first two examples (
if !), is often redundant. Any
nil value is ‘falsey’, so you can achieve the same result with a positive conditional and no
nil? check and substitute the
unless for an
if (example 1) or remove the
! (example 2) and end up with clearer code that means the same thing.
The syntax of
!!, in the third example, is shorthand for turning any value (either ‘truthy’ or ‘falsey’) into the actual boolean values
false. However, given Ruby’s ‘truthy’ conditionals performing this conversion is redundant.
This comes down to understandability. If you really are checking for
nil — perhaps you’re treating an empty array and
nil in different ways — then, by all means, explicitly use the check.
This article has been translated to Japanese.
photo by Jarrod Fitzgearlds
Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.