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



Question:

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?


Solution:1

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

EDIT: or false, thanks @mopoke.


Solution:2

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


Solution:3

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


Solution:4

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)  

or

@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
Previous
Next Post »