gpt4 book ai didi

ruby - 为什么 elsif 在 Ruby 中没有条件地工作?

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:07 25 4
gpt4 key购买 nike

为什么 elsif 没有传递评估条件就可以工作?看起来这应该会破坏我的代码,但事实并非如此。在其他语言中使用不带条件的 elsif 会中断,为什么 Ruby 不行?

x = 4

if x > 5
puts "This is true"
elsif
puts "Not true - Why no condition?"
end

返回

Not true - Why no condition?

在语句末尾添加 else 分支会同时返回 else 和 elsif 分支。

x = 4

if x > 5
puts "This is true"
elsif
puts "Not true - Why no condition?"
else
puts "and this?"
end

返回

Not true - Why no condition?
and this?

感谢您帮助我理解这个怪癖。

最佳答案

这是因为你的代码实际上解释为

if x > 5
puts "This is true"
elsif (puts "Not true - Why no condition?")
end

这里也一样

if x > 5
puts "This is true"
elsif (puts "Not true - Why no condition?")
else
puts "and this?"
end

puts在你的 elsif 中返回 nil,在打印 “Not true - Why no condition?” 之后,which(nil)是一个 falsy 值。因此 else 也被触发并且 "and this?" 也被打印出来。因此 2 个输出 Not true - Why no condition?and this?

关于ruby - 为什么 elsif 在 Ruby 中没有条件地工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com