rubyboolean

What's wrong with this simple boolean expression in Ruby?


Here is my Ruby 3.2 code:

puts (1 and 0)
puts (1 and 0 and 1)

It prints 0 and then 1 (I'm expecting 0 in both cases). Can someone explain, why?


Solution

  • First of all, and and or have very low precedence and are intended for control flow, e.g.

    do_this or exit
    

    (assuming do_this will return a truthy result upon success)

    For boolean operations, you should use && and || instead.

    Next, in Ruby there are two falsy values: false and nil. Every other value is considered truthy, including 0.

    You might be looking for:

    true && false
    #=> false
    
    true && false && true
    #=> false
    
    true && true && true
    #=> true
    

    If you are working with 1 and 0, bit operations might be useful: (see Integer#&)

    1 & 0
    #=> 0
    
    1 & 0 & 1
    #=> 0
    
    1 & 1 & 1
    #=> 1