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.
In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b.
It is the assignment operator used with hashes in ruby. So if you have a hash and want to assign a value to a key (typically a literal), use {key1 => value1, key2 => value2}
The and keyword in Ruby takes two expressions and returns “true” if both are true, and “false” if one or more of them is false. This keyword is an equivalent of && logical operator in Ruby, but with lower precedence.
||=
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With