Posted almost 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']

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

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