a ||= b
is a conditional assignment operator. It means:
- if
a
is undefined or falsey, then evaluateb
and seta
to the result. - Otherwise (if
a
is defined and evaluates to truthy), thenb
is not evaluated, and no assignment takes place.
For example:
a ||= nil # => nil
a ||= 0 # => 0
a ||= 2 # => 0
foo = false # => false
foo ||= true # => true
foo ||= false # => true
Confusingly, it looks similar to other assignment operators (such as +=
), but behaves differently.
a += b
translates toa = a + b
a ||= b
roughly translates toa || a = b
It is a near-shorthand for a || a = b
. The difference is that, when a
is undefined, a || a = b
would raise NameError
, whereas a ||= b
sets a
to b
. This distinction is unimportant if a
and b
are both local variables, but is significant if either is a getter/setter method of a class.
Further reading: