3

我有这个字符串数组:

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

4 回答 4

8
array.grep(query)

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

于 2013-06-03T14:47:43.990 回答
7

使用Enumerable#grep

matches = array.grep /nike/

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

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

或者,如果您希望您的用户能够使用特殊的正则表达式查询,只需:

matches = array.grep /#{my_str}/
于 2013-06-03T14:48:02.077 回答
2

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

def func( array )
  array.each_with_object [] do |string, return_array|
    return_array << string if string =~ /nike/
  end
end
于 2013-06-03T14:49:43.207 回答
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"]
于 2013-06-03T15:12:32.087 回答