The code foo ||= bar
is almost equivalent to foo = foo || bar
. In Ruby (as in many languages, like JavaScript or Io) boolean operators are "guard" operators. Instead of always returning true
or false
, they evaluate to the value of the first operand that evaluates to a "truthy" value.
For example, this code foo = 1 || delete_all_files_from_my_computer()
will not delete anything: foo will be set to 1
and the second operand won't even be evaluated.
In Ruby, the only "non-truthy" values are nil
and false
. So the code foo ||= bar
will only evaluate bar
and set foo
to the result if foo
is nil
or false
.
As instance variables default to nil
when not set, code like @foo ||= bar
is a common Ruby idiom to set the instance variable if it has not already been set.