What does ||= (or-equals) mean in Ruby?

a ||= b is a conditional assignment operator. It means:

  • if a is undefined or falsey, then evaluate b and set a to the result.
  • Otherwise (if a is defined and evaluates to truthy), then b 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 to a = a + b
  • a ||= b roughly translates to a || 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:

Leave a Comment