Posted about 4 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:

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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Judith Roth
Last edit:
about 1 year 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