What Ruby’s ||= (Double Pipe / Or Equals) Really Does

Updated . Posted . Visible to the public. Repeats.

It is a common misunderstanding that all [op]=-operators work the same way, but actually they don't.

||= and &&=

Those are special cases, because the assignment will only happen if the first variable passes the check (false or nil for || and true for &&).

a ||= b   # => a || (a = b)
a &&= b   # => a && (a = b)

But still, if reading a has any side effects, they will take place regardless of to what a resolves.

Other [op]=

Assignment will always take place, no matter the value of a.

a += b        # => a = a + b
a -= b        # => a = a - b
ary1 |= ary2  # => ary1 = ary1 | ary2

#...

For example array union:

ary1 = ['a', 'b', 'c']
ary2 = ['c', 'd', 'a']

ary1 |= ary2
# => ['a', 'b', 'c', 'd']
Profile picture of Judith Roth
Judith Roth
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2015-04-23 09:00)