如何从Ruby 2.0中的字符串数组中获取值

时间:2013-06-03 14:43:51

标签: ruby arrays

我有这个字符串数组:

array = [ "nike air", "nike steam","nike softy" ,"nike strength",
          "smooth sleeper","adidas air","addidas jogar","adidas softy","adidas heels"]

我想从中提取字符串,就像SQL一样查询。

例如,如果用户输入单词“nike”。然后应该返回4个字符串

           "nike air", "nike steam","nike softy" ,"nike strength"

例如,如果用户输入“adidas”字样。然后应该返回4个字符串

           "adidas air","addidas jogar","adidas softy","adidas heels"

有可能吗?

4 个答案:

答案 0 :(得分:8)

array.grep(query)

返回与查询匹配的数组子集。

答案 1 :(得分:7)

使用Enumerable#grep

matches = array.grep /nike/

添加/i以区分大小写。从字符串构造正则表达式:

re = Regexp.new( Regexp.escape(my_str), "i" )

或者,如果您希望用户能够使用特殊的Regexp查询,只需:

matches = array.grep /#{my_str}/

答案 2 :(得分:2)

或者您可以自己构建查询方法:

def func( array )
  array.each_with_object [] do |string, return_array|
    return_array << string if string =~ /nike/
  end
end

答案 3 :(得分:2)

array = [ "nike air", "nike steam","nike softy" ,"nike strength",
          "smooth sleeper","adidas air","addidas jogar","adidas softy","adidas heels"]
array.select{|i| i.include? "nike"}

# >> ["nike air", "nike steam", "nike softy", "nike strength"]