Read more

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

Judith Roth
April 23, 2015Software engineer at makandra GmbH

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

||= and &&=

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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']
Posted by Judith Roth to makandra dev (2015-04-23 11:00)