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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)