a ||= b is a conditional assignment operator. It means:
- if
ais undefined or falsey, then evaluateband setato the result. - Otherwise (if
ais defined and evaluates to truthy), thenbis 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 += btranslates toa = a + ba ||= broughly 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:
- http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html