It's hard to search this in google because it consists of symbol? What does ||= stand for? And how does it work?
Thanks.
It's hard to search this in google because it consists of symbol? What does ||= stand for? And how does it work?
Thanks.
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.)
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.
Cannot get any better explanation than The strange ||= operator :
a ||= "baseball"
a
will become"baseball"
if it wasnil
(orfalse
) before, otherwise it will just keep its original value.
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).