views:

46

answers:

2

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  A: 

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
vava
`each_with_index` would fit here: `i = ar.each_with_index {|e,i| i if e.include?(x)}`
glenn jackman
@glenn, `each_with_index` returns whole array. `p [1, 2].each_with_index {|e,i| i if e == 2} #-> [1, 2]`
vava
@vava: right. `i = ar.each_with_index.find {|e,i| e.include?(x)}[1]` ... not a big improvement over your answer.
glenn jackman
+4  A: 

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
Wayne Conrad