Posted about 3 years ago. Visible to the public. Repeats. External content.

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

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 resolves to the right value (false or nil for || and true for &&).

Shortcut operator What's actually happening
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.

Shortcut Operator What's actually happening
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']
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Author of this card:

Judith Roth
Last edit:
3 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Judith Roth to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more