开发者

Is it possible for WHEN to check the if the variable belongs to an array?

How can I do something like this开发者_如何学Go ? 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

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


Why don't you restructure you code a bit and do

ar = [["a","b"],["c"],["d","e"]]
x = "b"
i = (0...ar.length).find {|i| ar[i].include?(x)}
case i
    when 0
        puts "do something"
    when 1
        puts "do else"
    when 2
        puts "do a 3rd thing"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜