Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does a ||= mean in Ruby language? [duplicate]

Tags:

ruby

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.

like image 399
doel Avatar asked Mar 08 '11 08:03

doel


People also ask

What does ||= mean in ruby?

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.

What is arrow in ruby?

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}

What does and mean in ruby?

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.


1 Answers

||= 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.

like image 103
Matthew Scharley Avatar answered Oct 18 '22 02:10

Matthew Scharley