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

*爱你&永不变心* 提交于 2019-12-11 22:48:54

问题


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


来源:https://stackoverflow.com/questions/2109146/is-it-possible-for-when-to-check-the-if-the-variable-belongs-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!