49

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

How the |= assignment operator works?

4 Answers 4

81

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]
Sign up to request clarification or add additional context in comments.

Comments

57

Bitwise OR assignment.

x |= y

is shorthand for:

x = x | y

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

1 Comment

Bah, my bad, thanks for the correction. Updated my answer to reflect bitwise or, not logical or.
15

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

5 Comments

In what ways does x ||= y differ from x = x || y ?
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?
@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.
@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 &&.
Thank you @JörgWMittag for the detailed explanation!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.