The former returns “some string”, but the latter returns “a string”.
Apply that to the form you described and it basically means that if a
[:i] is nil then it assigns “a string”, otherwise it leaves it alone.
will return anotherObject (assuming it’s value isn’t nil)
The expression
a[:i] ||= “a string”
is equivalent to
a[:i] = a[:i] || “a string”
(sort of like ‘num+= 1’ is the same as ‘num = num + 1’)If a[:i] is not
nil then it will remain unchanged. If it is nil then it will be set to
“a string”.
“One serious obstacle to the adoption of good programming languages
is the notion that everything has to be sacrificed for speed. In
computer languages as in life, speed kills.” – Mike Vanier
I could not find this syntax in any manual online (and googling “||=” is
not of much help )
Can anyone tell me what it means
TiA
It is very useful as
var ||= expr
is a shortcut for
var = expr unless defined? var and var
which means if var is defined and evaluates to true it is left alone
however if var is not defined or evaluates to false it is assigned expr.
That means also that
var ||= expr
will overwrite nil and false values in var, a fact which seems to be
overseen sometimes.
Cheers
Robert
–
Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.