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
Share:
20,569
A B
Author by

A B

I'm building software.

Updated on April 12, 2021

Comments

  • A B
    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
    mynameiscoffey over 12 years
    Bah, my bad, thanks for the correction. Updated my answer to reflect bitwise or, not logical or.
  • mynameiscoffey
    mynameiscoffey over 12 years
    In what ways does x ||= y differ from x = x || y ?
  • Jeremy Moritz
    Jeremy Moritz about 3 years
    As far as i can tell, ||= and &&= are not exceptions. They both seem to function identically to a = a || b and a = a && b, respectively. If there are any exceptions to this, can you please provide an example?
  • Jörg W Mittag
    Jörg W Mittag about 3 years
    @JeremyMoritz: If a is a setter (e.g. foo.bar=), then a = a || b will always call both the setter and the getter, whereas a ||= b will only call the setter if a 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
    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 as a = a ω b, but that is only true for operators other than || and &&.
  • Jeremy Moritz
    Jeremy Moritz about 3 years
    Thank you @JörgWMittag for the detailed explanation!