Posted over 3 years ago. Visible to the public. Repeats. Linked 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:

Copy
ary1 = ['a', 'b', 'c'] ary2 = ['c', 'd', 'a'] ary1 |= ary2 # => ['a', 'b', 'c', 'd']

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Judith Roth
Last edit:
9 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