3

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.

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

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

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

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

Is it possible?

2
  • 3
    What code have you written to solve the problem? This is a pretty simple thing to do. Commented Jun 3, 2013 at 14:47
  • Not directly related but possibly relevant: SQL has a LIKE predicate, which allows you to pretty much do this but at the database layer. It might offer you a more flexible solution. Commented Jun 3, 2013 at 16:10

4 Answers 4

8
array.grep(query)

Returns the array subset that matches the query.

Sign up to request clarification or add additional context in comments.

3 Comments

array.grep('nike') gives be blank array
Try with Regexp instead of String.
@Kashiftufail i.e. /nike/ instead of 'nike'
7

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}/

2 Comments

@Phrogh matches = array.grep /nike/ give me accurate result but matches = array.grep /"nike"/ give me nothing. so how i should execute this code in my controller matches = array.grep /"#{params[:term]}"/ while params[:term] is string value
Use array.grep(Regexp.new(Regexp.escape(params[:term])))
2

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

2 Comments

Way more work (for both programmer and computer) than is necessary.
@Phrogz Definitely for programmer--is the implementation of grep C-ish? Otherwise wouldn't grep do much the same thing? I can't check at the moment.
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"]

2 Comments

@louism Perhaps you should explain your answer on the changes and how this approach is the "best" to resolve the OPS problem
This method is clearer. "Select the words that contain 'nike'" is simple, elegant and more idiomatic Ruby IMHO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.