what does a ||= mean in Ruby language? [duplicate]
Possible Duplicate:
What does ||= mean in Ruby?
what does the below line mean?
a ||= {}
a ||= 1
in irb it always returns the class of a, as hash, for both the above lines. Thanks in advance.
||=
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.
It means
a = a || {}
i.e.
a = {} unless a
you can read "a ||= {}" like this. If "a" is defined, then ignore the expression on the right side. Else, set "a" equals to the expression on the right side. In the first line, "a" is probably undefined so that line sets "a" to the expression on the right which is the empty hash. On the second line, "a" is already set as a {} so it is ignoring the expression on the right which has a value of 1.
精彩评论