tags:

views:

207

answers:

6

It's hard to search this in google because it consists of symbol? What does ||= stand for? And how does it work?

Thanks.

+2  A: 

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
+9  A: 

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
Looks a bit like the SQL `coalesce` operator
oxbow_lakes
Thanks. . . It just makes sure that the current value of the variable is not overwritten.
Marc Vitalis
+3  A: 

Cannot get any better explanation than The strange ||= operator :

a ||= "baseball"

a will become "baseball" if it was nil (or false) before, otherwise it will just keep its original value.

Mac
+5  A: 

From the question Common Ruby Idioms:

is equivalent to

 if a == nil || a == false   
    a = b 
 end
flicken
A: 

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  A: 

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