What does ||= (or-equals) mean in Ruby?

ghz 1years ago ⋅ 5371 views

Question

What does the following code mean in Ruby?

||=

Does it have any meaning or reason for the syntax?


Answer

This question has been discussed so often on the Ruby mailing-lists and Ruby blogs that there are now even threads on the Ruby mailing-list whose only purpose is to collect links to all the other threads on the Ruby mailing- list that discuss this issue.

Here's one: [The definitive list of ||= (OR Equal) threads and pages](https://www.ruby-forum.com/t/the-definitive-list-of-or-equal-threads- and-pages/136446)

If you really want to know what is going on, take a look at Section 11.4.2.3 "Abbreviated assignments" of the Ruby Language Draft Specification.

As a first approximation,

a ||= b

is equivalent to

a || a = b

and not equivalent to

a = a || b

However, that is only a first approximation, especially if a is undefined. The semantics also differ depending on whether it is a simple variable assignment, a method assignment or an indexing assignment:

a    ||= b
a.c  ||= b
a[c] ||= b

are all treated differently.