What does this assignment operator |=


S

Stefan Achatz

Hello,
i think i once saw an assignment operator |= used in a ruby program.
I can't find anything in the pickaxe-book and on google.
What does it do?
Thanks, Stefan
 
Ad

Advertisements

W

Wolfgang Nádasi-Donner

Stefan Achatz said:
Hello,
i think i once saw an assignment operator |= used in a ruby program.
I can't find anything in the pickaxe-book and on google.
What does it do?
Thanks, Stefan

'a |= b' is the same as 'a = a | b', where '|' is the or-method. There is one remarkable difference to '||'
(and '||='), because '||' may be lazy if the left operand evaluates to 'true', while using the '|'-method the
right operand is an argument for the method, so it will always be evaluated.

Best regards, Wolfgang
 
A

Adriano Ferreira

i think i once saw an assignment operator |=3D used in a ruby program.
I can't find anything in the pickaxe-book and on google.
What does it do?

Easily,=20
a |=3D b
is the same as
a =3D a | b
and | is bit-or.

It works just like you would expect

a =3D 3 # 0...011 in binary
a |=3D 4 # 0..0100 in binary
p a # prints 7 which 0..000111 in binary
 
A

Austin Ziegler

Hello,
i think i once saw an assignment operator |=3D used in a ruby program.
I can't find anything in the pickaxe-book and on google.
What does it do?
Thanks, Stefan

It does the same as foo =3D foo | bar, where | is the bitwise operator.

It's more common to see foo ||=3D bar, which is foo =3D foo || bar.

-austin
--=20
Austin Ziegler * (e-mail address removed)
* Alternate: (e-mail address removed)
 
A

Adriano Ferreira

Well, it looks there are more to the meaning of the operator | as ri shows

$ ri "|"
More than one method matched your request. You can refine
your search by asking for information on one of:

Array#|, Bignum#|, FalseClass#|, Fixnum#|, NilClass#|, Set#|,
TrueClass#|

Each of these classes has | implementations, which should be related
one way or the other to the simple meaning of bit-or.

Regards,
Adriano.
 
Ad

Advertisements

N

Nikolai Weibull

Easily,
a |= b
is the same as
a = a | b
and | is bit-or.

Well, not necessarily. For an array, the | operator is used to create
the (unique) union of the array and a second argument array,
nikolai
 
Ad

Advertisements


Top