2014-02-20 40 views
2

這甚至可能與switch case?我看了帖子here,但它不適應。當案件包括在陣列

step = 'a' 
arr = ['a', 'b', 'c'] 

case step 
when arr.include? 
    puts "var is included in array" 
when "other" 
    puts "nothing" 
end 

回答

8

when條款可以接受多個值:

case step 
when *arr 
    puts "var is included in array" 
when "other" 
    puts "nothing" 
end 
+0

感謝。這個怎麼用?這是數組或其他東西的'splat'嗎? –

+0

@ElijahMurray:是的,這只是一個正常的圖示。 – Chuck

2

你可以提供一個進程的case語句:

case step 
when ->(x){ arr.include?(x) } 
    puts "var is included" 
when "other" 
    puts "nothing" 
end 

這工作,因爲紅寶石使用===運營商確定的平等case語句,並且Proc#===使用比較值作爲參數來執行proc。所以:

arr = [1,2,3] 
proc = ->(x){ arr.include?(x) } 
proc === 2 #=> true 

...雖然我很喜歡@查克的摔跤運營商爲這種特殊情況。

3

此選項值得一提:

step = 'a' 
arr = ['a', 'b', 'c'] 
case 
when arr.include?(step) 
    puts "arr matches" 
when arr2.include?(step) 
    puts "arr2 matches" 
end 
+0

我確認這個作品。 – wurde