2010-01-21 10 views

Répondre

4

Il est non seulement possible, il est facile. Pour des tableaux constants:

#!/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 

Ou, si les tableaux ne sont pas constantes:

#!/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 
1

Pourquoi restructurer code-vous pas un peu et faire

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

'each_with_index' cadrerait ici:' i = {ar.each_with_index | e, i | Si e.include? (x)} ' –

+0

@ glenn,' each_with_index' renvoie un tableau entier. 'p [1, 2] .each_with_index {| e, je | i si e == 2} # -> [1, 2] ' – vava

+0

à droite. 'i = ar.each_with_index.find {| e, je | e.include? (x)} [1] '... pas une grande amélioration par rapport à votre réponse. –