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
答案 0 :(得分:8)
when
子句可以接受多个值:
case step
when *arr
puts "var is included in array"
when "other"
puts "nothing"
end
答案 1 :(得分:3)
这个选项值得一提:
step = 'a'
arr = ['a', 'b', 'c']
case
when arr.include?(step)
puts "arr matches"
when arr2.include?(step)
puts "arr2 matches"
end
答案 2 :(得分:2)
您可以为案例陈述提供过程:
case step
when ->(x){ arr.include?(x) }
puts "var is included"
when "other"
puts "nothing"
end
这是有效的,因为ruby使用===
运算符来确定case语句中的相等性,Proc#===
使用比较值作为参数来执行proc。所以:
arr = [1,2,3]
proc = ->(x){ arr.include?(x) }
proc === 2 #=> true
...虽然我更喜欢这个特殊情况的@ Chuck的splat运算符。