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.
Last updated on December 31st, 2017 by @andycroll
An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.