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?

0

5 Answers 5

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.

4
  • 1
    Looks a bit like the SQL coalesce operator Sep 7, 2009 at 12:13
  • Thanks. . . It just makes sure that the current value of the variable is not overwritten. Sep 8, 2009 at 2:53
  • This is nice. Something C# can inspire from. :-) Oct 3, 2012 at 17:53
  • 1
    Note that both nil and false are falsey. So if the values you work with are boolean, it won't distinguish "unassigned" from "assigned to false", later a ||= true will override existing false value. (Unlike SQL coalesce() ternary logic: db-fiddle.com/f/6JMNY7TLVEgTa4GdWg74Sc/0) Jan 12, 2020 at 13:53
10

From the question Common Ruby Idioms:

is equivalent to

 if a == nil || a == false   
    a = b 
 end
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).

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.