tags:

views:

133

answers:

4
+2  Q: 

Noob Ruby notation

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

foo ||= bar

What is it?

+4  A: 

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

EDIT: or false, thanks @mopoke.

Peter
Or if foo is false.
mopoke
+1  A: 

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

mopoke
Should be: unless `foo` is truthy, where truthy means: not `false` or `nil`.
Justice
+6  A: 

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

shedd
A: 

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

Andrew Grimm