||=
is an assignment operator, which returns the value assigned. a ||= b
is equivalent to the statement a || a = b
which means that if a
is set and has some true value, then it remains the same, otherwise it takes the value of b
.
In your example a
is only ever set once, which explains the behaviour you've noticed.
a ||= {}
a ||= 1 // a is still {}
Typical usage I've seen is to initialise static variables, ie.
class Foo
def self.bar
return @bar ||= {}
end
end
EDIT:
It bears mentioning that ||=
is a short-circuit operator. This means that it in the case of a ||= b
there will only be an assignment of a = b
. There will never be an assignment of a = a
in the case that a
is non-false. This is a little pedantic, but matters in some (very) edge cases.
For more information, read the definitive list of ||= threads and pages.