6

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

foo ||= bar

What is it?

Jan Wikholm
  • 1,557
  • 1
  • 10
  • 19
user94154
  • 16,176
  • 20
  • 77
  • 116

4 Answers4

9

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

EDIT: or false, thanks @mopoke.

Peter
  • 127,331
  • 53
  • 180
  • 211
7

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
  • 4,198
  • 4
  • 33
  • 42
2

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

mopoke
  • 10,555
  • 1
  • 31
  • 31
1

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
  • 78,473
  • 57
  • 200
  • 338