patternrubyCritical
What does ||= (or-equals) mean in Ruby?
Viewed 0 times
rubydoesmeanequalswhat
Problem
What does the following code mean in Ruby?
Does it have any meaning or reason for the syntax?
||=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,
is equivalent to
and not equivalent to
However, that is only a first approximation, especially if
are all treated differently.
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 ||= bis equivalent to
a || a = band not equivalent to
a = a || bHowever, 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] ||= bare all treated differently.
Code Snippets
a ||= b
a.c ||= b
a[c] ||= bContext
Stack Overflow Q#995593, score: 180
Revisions (0)
No revisions yet.