Ruby |= assignment operator
20,569
Solution 1
Bitwise OR assignment.
x |= y
is shorthand for:
x = x | y
(just like x += y
is shorthand for x = x + y
).
Solution 2
When working with arrays |= is useful for uniquely appending to an array.
>> x = [1,2,3]
>> y = [3,4,5]
>> x |= y
>> x
=> [1, 2, 3, 4, 5]
Solution 3
With the exception of ||=
and &&=
which have special semantics, all compound assignment operators are translated according to this simple rule:
a ω= b
is the same as
a = a ω b
Thus,
a |= b
is the same as
a = a | b
Solution 4
It is listed in the link you provided. It's an assignment combined with bitwise OR. Those are equivalent:
a = a | b
a |= b
Comments
-
A B about 3 years
Found table http://phrogz.net/programmingruby/language.html#table_18.4 but unable to find description for
|=
How the
|=
assignment operator works? -
mynameiscoffey over 12 yearsBah, my bad, thanks for the correction. Updated my answer to reflect bitwise or, not logical or.
-
mynameiscoffey over 12 yearsIn what ways does
x ||= y
differ fromx = x || y
? -
Jeremy Moritz about 3 yearsAs far as i can tell,
||=
and&&=
are not exceptions. They both seem to function identically toa = a || b
anda = a && b
, respectively. If there are any exceptions to this, can you please provide an example? -
Jörg W Mittag about 3 years@JeremyMoritz: If
a
is a setter (e.g.foo.bar=
), thena = a || b
will always call both the setter and the getter, whereasa ||= b
will only call the setter ifa
is falsey (or truthy in the case of&&=
). In other words: I can write a program which can output whether you used||=
or= … || …
, therefore the two are not equivalent. -
Jörg W Mittag about 3 years@JeremyMoritz: Note that this is a bug in the ISO Ruby Language Specification. The ISO spec says that all operator assignments
a ω= b
for all operatorsω
are evaluated AS-IF they were written asa = a ω b
, but that is only true for operators other than||
and&&
. -
Jeremy Moritz about 3 yearsThank you @JörgWMittag for the detailed explanation!