KhiemNS KhiemNS - 2 months ago 16
Ruby Question

ruby why 0 || 1 is 0

AND operator return second value when the first is true, the first one when it's false

1 && 2 ---> 2
0 && 1 ---> 0


why OR operation not return second value when the first one is false, but return the first one when it's true

0 || 1 ---> 0
1 || 0 ---> 1

Answer

Ruby only evaluates as much as it needs to in an expression like this and then stops, what you are seeing returned is just the last part of the expression that it evaluated. So for your && case, it always has to run right to the end in case a later clause returns false and which would cause the AND to be false.

And actually your example is wrong:

irb> 0 && 1
=> 1

Which is expected since 0 is truthy in Ruby, not as false like in C.

For the OR case, it can stop as soon as it hits anything that is truthy and doesn't need to bother with the rest.

0 || false      # => 0
false || 0      # => 0
false || 0 || 2 # => 0

If you want to force an expression like this to a boolean this is how you often see it done:

!!(expression)
!!(0 || 1)        => true
!!(nil || false)  => false 
Comments