45

Found table http://phrogz.net/programmingruby/language.html#table_18.4 but unable to find description for |=

How the |= assignment operator works?

Cœur
  • 37,241
  • 25
  • 195
  • 267
A B
  • 2,013
  • 2
  • 21
  • 22

4 Answers4

77

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]
mlm
  • 870
  • 6
  • 3
53

Bitwise OR assignment.

x |= y

is shorthand for:

x = x | y

(just like x += y is shorthand for x = x + y).

mynameiscoffey
  • 15,244
  • 5
  • 33
  • 45
14

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
Jeremy Moritz
  • 13,864
  • 7
  • 39
  • 43
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 1
    In what ways does `x ||= y` differ from `x = x || y` ? – mynameiscoffey Dec 20 '11 at 15:57
  • 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? – Jeremy Moritz Apr 11 '21 at 14:41
  • 2
    @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 Apr 11 '21 at 15:22
  • 2
    @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 `&&`. – Jörg W Mittag Apr 11 '21 at 15:25
  • Thank you @JörgWMittag for the detailed explanation! – Jeremy Moritz Apr 12 '21 at 00:16
3

It is listed in the link you provided. It's an assignment combined with bitwise OR. Those are equivalent:

a = a | b
a |= b
ScarletAmaranth
  • 5,065
  • 2
  • 23
  • 34