Julian A Avar C
Julian A Avar C

Reputation: 878

Whats the dfference between ||= and |= with booleans

I understand that a ||= b behaves like a || a = b and that a |= b behaves like a = a | b

When working with booleans, does it make a difference which you use? I presume that the only practical difference is that ||= will not assign if a and b are true, is that the only difference?

Upvotes: 1

Views: 76

Answers (2)

Salil
Salil

Reputation: 47512

While Oring if any statement is true then completed statement will return true only. Similarly, while Anding if any statement is false then completed statement will return false only.

The major difference between || & | is when first statement of || is truthy the other statements not execute. Whereas | will execute all the statements even if the first statements is truthy.

Consider following example for ||

2.6.5 :001 > a = 4
 => 4
2.6.5 :002 > a ||= (b = 9) # same as a = 4 || 9
 => 4
2.6.5 :003 > a
 => 4
2.6.5 :004 > b
 => nil

example for | (For int | other_int it will do the bitwise OR ref )

2.6.5 :005 > c = 6
 => 6
2.6.5 :006 > c |= (d = 8) # same as a = 0110 || 1110
 => 14
2.6.5 :007 > c
 => 14
2.6.5 :008 > d
 => 8

For Boolean Example for ||

2.6.5 :001 > a = true
 => true
2.6.5 :002 > a ||= (b = false)
 => true
2.6.5 :003 > a
 => true
2.6.5 :004 > b
 => nil

Example for |

2.6.5 :005 > c = true
 => true
2.6.5 :006 > c |= (d = false)
 => true
2.6.5 :007 > c
 => true
2.6.5 :008 > d
 => false

Upvotes: 1

tadman
tadman

Reputation: 211660

That's not quite right. In general the X= operator behaves like A = A X B where X is one of the supported operators. Notably it's always on the right side of the =.

That being said, | and || are two very different operators. The | version is typically understood to do binary math, as in:

2 | 1
# => 3

Where that's the result of 0b10 and 0b01 being combined with a binary OR.

It also does array unions:

[ 1, 2 ] | [ 2, 3 ]
# => [ 1, 2, 3 ]

Whereas || a higher level logical test on the truthiness of values. In Ruby only nil and false are considered non-truthful, all other values are considered truthful, so:

0 || 1
# => 0
false || true
# => true
nil || "yes"
# => "yes"

The same principle applies to & and &&.

Interestingly | and & are method calls and their actual functionality depends on what's on the left side of the operator, while || and && are syntactic elements you cannot change and always work the same way.

So where do |= and ||= come into play? There's a few cases where you'll see them.

Setting bitflags:

flags |= 0b0010

Applying defaults:

max ||= MAX_DEFAULT

Upvotes: 2

Related Questions