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)
如评论中所述,检查运算符优先级。
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |