ruby将字符串匹配到字符串数组

时间:2012-10-15 15:31:23

标签: ruby arrays

  

可能重复:
  In Ruby, how do I find out if a string is not in an array?

现在我有了这段代码:

partial_update = true if session[:intended_params][:controller] == 'foo'
partial_update = true if session[:intended_params][:controller] == 'bar'
partial_update = true if session[:intended_params][:controller] == 'ding'
partial_update = true if session[:intended_params][:controller] == 'dong'
partial_update = true if session[:intended_params][:controller] == 'up'
partial_update = true if session[:intended_params][:controller] == 'down'
partial_update = true if session[:intended_params][:controller] == 'bing'
# ETC. 

我想将此更改为

array = %w[foo bar ding dong up down bing]
partial_update = true if session[:intended_params][:controller]  == array.any_of_the_possibilites

有没有好办法呢?

2 个答案:

答案 0 :(得分:5)

使用Ruby Array (Enumerable) include? method

array = %w[foo bar ding dong up down bing]
partial_update = true if array.include?(session[:intended_params][:controller])

答案 1 :(得分:1)

case session[:intended_params][:controller]
when *%w[foo bar ding dong up down bing]
  partial_update =  true
end

可能会滥用case声明