HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
rubydoesmeanequalswhat

Problem

What does the following code mean in Ruby?

||=


Does it have any meaning or reason for the syntax?

Solution

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

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.

Code Snippets

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

Context

Stack Overflow Q#995593, score: 180

Revisions (0)

No revisions yet.