26

Possible Duplicate:
What does ||= (or equals) mean in Ruby?

It's hard to search this in Google because it is a symbol, not text.

What does ||= stand for?

And how does it work?

Community
  • 1
  • 1
Marc Vitalis
  • 2,129
  • 4
  • 24
  • 36

5 Answers5

32

It assigns a value if not already assigned. Like this:

a = nil
a ||= 1

a = 1
a ||= 2

In the first example, a will be set to 1. In the second one, a will still be 1.

peku
  • 5,003
  • 3
  • 20
  • 15
10

From the question Common Ruby Idioms:

is equivalent to

 if a == nil || a == false   
    a = b 
 end
Community
  • 1
  • 1
flicken
  • 15,443
  • 4
  • 29
  • 29
1

If b is nil, assign a to it.

a = :foo
b ||= a
# b == :foo

If b is not nil, don't change it.

a = :foo
b = :bar
b ||= a
# b == :bar
1

This is an 'abbreviated assignment' (see Ruby Pocket Reference, page 10)

a = a || b

(meaning a is assigned the value formed by logical or of a, b

becomes

a ||= b

Almost all operators have an abbreviated version (+= *= &&= etc).

pavium
  • 14,808
  • 4
  • 33
  • 50
0

i can only guess, but i assume it stands for an logical operator combined with setting a variable (like ^=, +=, *= in other languages)

so x ||= y is the same as x = x || y

edit: i guessed right, see http://phrogz.net/ProgrammingRuby/language.html#table_18.4

x = x || y means: use x if set, otherwise assign y. it can be used to ensure variables are at least initialised (to 0, to an empty array, etc.)

knittl
  • 246,190
  • 53
  • 318
  • 364