简体   繁体   中英

How get value from array of strings in Ruby 2.0

I have this array of strings:

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

I want to extract strings from this as SQL like query.

Eg if user enter word "nike". Then 4 strings should be return as result

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

Eg if user enter word "adidas". Then 4 strings should be return as result

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

Is it possible?

array.grep(query)

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

Use Enumerable#grep :

matches = array.grep /nike/

Add /i for case insensitive. To construct a regexp from a string:

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

Or, if you want your users to be able to use special Regexp queries, just:

matches = array.grep /#{my_str}/

Or you can build your query method by yourself:

def func( array )
  array.each_with_object [] do |string, return_array|
    return_array << string if string =~ /nike/
  end
end
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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM