Car*_*ine 4 ruby conditional-operator operator-precedence
我得到以下内容:
puts true or true and false
# >> true
Run Code Online (Sandbox Code Playgroud)
而我也得到:
if true or true and false
puts "that's true!"
else
puts "that's false!"
end
# >> that's false!
Run Code Online (Sandbox Code Playgroud)
为什么true or true and false两者都true和false(像薛定谔的猫一样)?
它与优先权有关.puts true or true and false实际上评估为(puts true) or (true and false) [编辑:不完全.请参阅下面Todd的注释.],并if true or true and false评估为if (true or (true and false)).这是由于puts(方法)和if(语言关键字)相对于表达式的其他项的优先级.
=> false当你评估时,你会在irb中看到puts true or true and false(记住,那是(puts true) or (true and false))因为puts输出true和返回nil,这是假的,导致(true and false)接下来评估,返回false.
这就是大多数Ruby指南推荐使用&&而||不是and和or布尔表达式的原因之一.按照您的预期puts true || true && false评估puts (true || (true && false))和if true || true && false评估if (true || (true && false)).
| 归档时间: |
|
| 查看次数: |
606 次 |
| 最近记录: |