Is it possible for WHEN to check the if the variab

2019-09-08 05:07发布

问题:

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

I'm using ruby 1.8.7

回答1:

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


回答2:

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