正如我在逻辑中一直被教导的那样,and运算符意味着这两个值都必须为true,才能使整个语句变为true。如果您有许多与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认为地球是平的?
发布于 2022-01-15 20:59:11
尽管你希望这样:
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正如注释中所指出的,请查看运算符优先。
https://stackoverflow.com/questions/70725308
复制相似问题