[Talking-Ruby] Double Pipe (||) Or Equals (=) in Ruby

a ||= b VS a = a || b VS a || a = b, Double Pipe (||) Or Equals (=) in Ruby

A common misconception is that a ||= b is equivalent to a = a || b, but it behaves like a || a = b

In a = a || b, a is set to something by the statement on every run, whereas with a || a = b, a is only set if a is logically false (i.e. if it’s nil or false) because || is ‘short circuiting’. That is, if the left hand side of the || comparison is true, there’s no need to check the right hand side.


Do not confuse [op]= with anything related to ||= or &&=. They’re entirely different ideas and are implemented entirely different.


Undefined Variables Tricky Case

If a is not defined, a || a = 42 raises NameError, while a ||= 42 returns 42. So, they don’t seem to be equivalent expressions.

1
a || a = 42 # NameError (undefined local variable or method `a' for main:Object)

Even though the first line won’t be run, x will exist on the second line and no exception will be raised

1
2
x = 10 if 2 == 5
puts x # nil

Ruby sees the assignment at the parsing stage and creates the variable in a way.

1
2
3
4
5
x = x
puts x

a ||= 42
puts a

References

[1] http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html - http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html