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