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

Col*_*gan 3 ruby conditional-statements

正如我一直接受的逻辑教育一样,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
Run Code Online (Sandbox Code Playgroud)

奇怪的是,如果我只是运行语句本身,它会正确返回 falseputs(horizon_flat and one_up_and_down and magellan_fell) # false

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

Chr*_*ris 10

当你期望这样的时候:

flat_earth_thesis = horizon_flat and one_up_and_down and magellan_fell
Run Code Online (Sandbox Code Playgroud)

需评估为:

flat_earth_thesis = (horizon_flat and one_up_and_down and magellan_fell)
Run Code Online (Sandbox Code Playgroud)

相反,它被评估为:

(flat_earth_thesis = horizon_flat) and one_up_and_down and magellan_fell
Run Code Online (Sandbox Code Playgroud)

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

  • 这就是为什么在 Ruby 风格指南中通常遵循“&&”而不是“and”。由于 `&&` 的优先级高于 `=`,因此 `a = b && c && d` 按照您的预期工作。 (3认同)