WHEN是否可以检查变量是否属于数组? [英] Is it possible for WHEN to check the if the variable belongs to an array?
本文介绍了WHEN是否可以检查变量是否属于数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么做?还是我需要一直使用IF?
How can I do something like this ? or do i need to use IF all the time?
ar = [["a","b"],["c"],["d","e"]]
x = "b"
case x
when ar[0].include?(x)
puts "do something"
when ar[1].include?(x)
puts "do else"
when ar[2].include?(x)
puts "do a 3rd thing"
end
我正在使用ruby 1.8.7
I'm using ruby 1.8.7
推荐答案
不仅可行,而且很容易.对于常量数组:
It's not only possible, it's easy. For constant arrays:
#!/usr/bin/ruby1.8
x = "a"
case x
when 'a', 'b'
puts "do something" # => do something
when 'c'
puts "do else"
when 'd', 'e'
puts "do a 3rd thing"
end
或者,如果数组不是恒定的:
Or, if the arrays aren't constant:
#!/usr/bin/ruby1.8
ar = [["a","b"],["c"],["d","e"]]
x = 'd'
case x
when *ar[0]
puts "do something"
when *ar[1]
puts "do else"
when *ar[2]
puts "do a 3rd thing" # => do a 3rd thing
end
这篇关于WHEN是否可以检查变量是否属于数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文