The ||= Operator in Ruby
14 Jan 2018
The ||= operator in Ruby is something that gets talked about all the time. Here is a just a small sample of links that talk about how exactly the ||= operator really works. There is even a link on the Ruby mailing list which just collects links that discuss this operator. Needless to say, ||= has caused some confusion.
What most people think that ||= would do is this:
a = a || b
This makes sense given how operators such as += and -= works. However, it is actually closer to
a || a = b
In words, if a has a falsey value (i.e. nil or false) then set a to b. Otherwise, do nothing.
Note that with a || a = b, the assignment only occurs if a has a falsey value. With
a = a || b, the assignment occurs regardless of a's value.
This is an easy way to think about how the operator works, but in some cases, a || a = b and a ||= b
behave differently. For example, if a is undefined, then
a || a = 42
will result in an error but
a ||= 42
will assign a to 42.
While reading these posts, I also learned a bit about when and when you might get a NameError. If,
in some nested scope, you assign to a variable, you can later refer to that variable without getting
an error, even if that line of code doesn't get called. For example:
def f
x
end
def g
if false
x = 1
end
x
end
Calling f here will give you a NameError, while calling g will not.
If you're interested in learning more, read some of the links! They have good information, as well as links to other sources with more information.