Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using "and" in Ruby, the earth is flat

As I have always been taught in logic, the and operator means both values must be true, for the entire statement to be true. If you have many statements chained with and, then any one of them being false should make the whole claim false. In Ruby, however, I ran into this scenario:

horizon_flat = true
one_up_and_down = true
magellan_fell = false
flat_earth_thesis = horizon_flat and one_up_and_down and magellan_fell

puts("Hey ruby, doesn't the horizon look flat?")
puts(horizon_flat) # true

puts("Isn't there only one up and one down?")
puts(one_up_and_down) # true

puts("Did Magellan fall off the earth?")
puts(magellan_fell) # false

puts("Is the earth flat?")
puts(flat_earth_thesis) # true

Strangely, if I just run the statement itself, it returns false correctly puts(horizon_flat and one_up_and_down and magellan_fell) # false

But if I store that statement in a variable, and later call it, the variable outputs true. Why does Ruby think the earth is flat?

like image 980
Colin Brogan Avatar asked Dec 05 '25 06:12

Colin Brogan


1 Answers

While you expect this:

flat_earth_thesis = horizon_flat and one_up_and_down and magellan_fell

To be evaluated as:

flat_earth_thesis = (horizon_flat and one_up_and_down and magellan_fell)

It is instead evaluated as the following, since and has lower precedence than =.

(flat_earth_thesis = horizon_flat) and one_up_and_down and magellan_fell

You likely wanted the following, since && is higher precedence than =.

flat_earth_thesis = horizon_flat && one_up_and_down && magellan_fell

As noted in comments, review operator precedence.

like image 77
Chris Avatar answered Dec 07 '25 02:12

Chris