Boolean inconsistency

Running the following code:

stmt = true and false
puts "stmt = true and false: " + stmt.to_s

stmt = false and true
puts "stmt = false and true: " + stmt.to_s

if true and false
  stmt = true
else
  stmt = false
end
puts "if true and false: " + stmt.to_s

if false and true
  stmt = true
else
  stmt = false
end
puts "if false and true: " + stmt.to_s

… results in the following output:

{run: 89, time: 0.0}
 ├─ "stmt = true and false: true"
 ├─ "stmt = false and true: false"
 ├─ "if true and false: false"
 └─ "if false and true: false"

Maybe I have had a drink too much, but anyhow there’s something I don’t quite get here… :thinking: :wine_glass:

Please explain somebody.

This is due to Ruby’s precedence ordering. You typically want to avoid and and prefer && instead. For more information see: operators - Difference between "and" and && in Ruby? - Stack Overflow.

1 Like