J
Justin To
what does ||= do?
what does ||= do?
what does ||= do?
a ||= b is shorthand for a = a || b
|| is the "or" operator - a || b evaluates to a unless a is nil or
false, in which case it evaluates to b
a ||= b is most commonly used to say "if a hasn't already been set
(and is therefore nil), set it to b, else leave it alone"
martin
The expression:
x ||= y
is shorthand for:
x = x || y
where "||" is the OR-operator. If x evaluates as false or nil, the
value of y will be assigned to x; otherwise, x keeps its original
value. So, for example,
x = nil
x ||= 42 # now x has value 42
x ||= 23 # x stays at 42
Hope this helps,
Lyle
The expression:
x ||= y
is shorthand for:
x = x || y
where "||" is the OR-operator. If x evaluates as false or nil, the
value of y will be assigned to x; otherwise, x keeps its original
value. So, for example,
x = nil
x ||= 42 # now x has value 42
x ||= 23 # x stays at 42
Justin said:what does ||= do?
this really is equivalent to a =3D a || b, just like a +=3D 1 is =20
equivalent to a =3D a + 1 (same for -=3D, etc.
=3D> falseh[:a] =3D> "default"
h.has_key? :a
=3D> falseh[:a] ||=3D "not default" =3D> "default"
h[:a] =3D> "default"
h.has_key? :a
h[:a] =3D h[:a] || "not default" =3D> "default"
h[:a] =3D> "default"
h.has_key? :a =3D> true
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.