2014-02-09 32 views
2

爲什麼elsif在沒有通過條件評估的情況下工作?看起來這應該會破壞我的代碼,但它不會。在其他語言中使用沒有條件的elsif,爲什麼不使用Ruby?爲什麼elsif在Ruby中沒有條件工作?

x = 4 

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

回報

Not true - Why no condition? 

的語句返回兩個其他和ELSIF分支的末端添加一個else分支。

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? 

感謝您幫助我理解這個怪癖。

回答

4

這是因爲你的代碼也在這裏

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

putselsif回報nil,打印後竟解釋爲

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

同樣的 「事實並非如此 - 爲什麼沒有條件?」,其中(nil)是falsy的值。因此else也被觸發並且"and this?"也被打印。因此2個輸出Not true - Why no condition?and this?

2

因爲puts被用作測試表達式。 puts返回nil;控制繼續到下一個elsif/else

x = 4 

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

這是一樣的:

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

putselsif返回nil,這是一個錯誤的值,因此else被觸發。

相關問題