在 Ruby 中使用“and”时,地球是平的

问题描述 投票:0回答:1

正如我一直接受的逻辑教育一样,

and
运算符意味着两个值都必须为真,整个语句才为真。如果您有许多与
and
相关的陈述,那么其中任何一项为假都会导致整个声明为假。然而,在 Ruby 中,我遇到了这种情况:

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

奇怪的是,如果我只是运行语句本身,它会正确返回 false

puts(horizon_flat and one_up_and_down and magellan_fell) # false

但是如果我将该语句存储在一个变量中,然后调用它,该变量将输出 true。为什么鲁比认为地球是平的?

ruby conditional-statements
1个回答
10
投票

当你期待这个时:

flat_earth_thesis = horizon_flat and one_up_and_down and magellan_fell

评估为:

flat_earth_thesis = (horizon_flat and one_up_and_down and magellan_fell)

它被评估为:

(flat_earth_thesis = horizon_flat) and one_up_and_down and magellan_fell

您可能想要:

flat_earth_thesis = horizon_flat && one_up_and_down && magellan_fell

如评论中所述,请查看运算符优先级

© www.soinside.com 2019 - 2024. All rights reserved.