为什么elsif在Ruby中没有条件的情况下工作?

bea*_*ets 3 ruby

为什么elsif在没有通过评估条件的情况下工作?看起来这应该会破坏我的代码,但事实并非如此.在没有条件的情况下使用elsif会破坏其他语言,为什么不使用Ruby?

x = 4

if x > 5
puts "This is true"
elsif
puts "Not true - Why no condition?"
end
Run Code Online (Sandbox Code Playgroud)

回报

Not true - Why no condition?
Run Code Online (Sandbox Code Playgroud)

在语句末尾添加else分支将返回else和elsif分支.

x = 4

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

回报

Not true - Why no condition?
and this?
Run Code Online (Sandbox Code Playgroud)

谢谢你帮我理解这个怪癖.

Aru*_*hit 7

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

if x > 5
  puts "This is true"
elsif (puts "Not true - Why no condition?")
end
Run Code Online (Sandbox Code Playgroud)

同样也在这里

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

puts在你的elsif回报中nil,打印后"不正确 - 为什么没有条件?" ,(nil)是一个falsy值.因此else也被触发并且"and this?"也被打印.因此2输出Not true - Why no condition?and this?.