Tutorial :What does ||= do in Ruby [duplicate]


This question already has an answer here:

I've been using Ruby for a while now, and I keep seeing this:

foo ||= bar  

What is it?


This will assign bar to foo if (and only if) foo is nil or false.

EDIT: or false, thanks @mopoke.


Operator ||= is a shorthand form of the expression:

x = x || "default"

Operator ||= can be shorthand for code like:

x = "(some fallback value)" if x.nil?

From: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators


Assign bar to foo unless foo is a true value (not false or nil).


If you're using it for an instance variable, you may want to avoid it. That's because

@foo ||= bar  

Can raise a warning if @foo was previously uninitialized. You may want to use

@foo = bar unless defined?(@foo)  


@foo = bar unless (defined?(@foo) and @foo)  

depending on whether you want to merely check if @foo is initialized, or check if @foo has truthiness (ie isn't nil or false).

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »