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

为什么elsif在Ruby中没有条件工作?,ruby,Ruby,为什么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? Not true - Why no condition? and this? 在语句末尾添加el

为什么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?
Not true - Why no condition?
and this?
在语句末尾添加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?
Not true - Why no condition?
and this?

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

因为
put
被用作测试表达式<代码>卖出返回
nil
;控件继续下一步
elsif
/
else

x = 4

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

放入您的
elsif
中,返回nil,这是一个假值,因此触发
else

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

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
在您的
elsif
中,在打印“不正确-为什么没有条件?”后返回
nil
,其中(
nil
)是
falsy
值。因此,
else
也会被触发,
“这是什么?”
也会被打印出来。因此,2个输出
不正确-为什么没有条件?
以及此?