2

I have a list of objects that I want to filter by a parameter in the URL.

So for example:

@items = items.select { |item| params[:q] == item.name }

However this will match EXACT... how can I make it behave as a LIKE?

2
  • What does "as a LIKE" mean? Is "formula" like "or"? Does it make a difference that the parameter is "in the URL" (whatever "the URL" refers to)? This question begs for examples. I've downvoted but will remove it if the question is clarified. Commented Sep 15, 2016 at 17:31
  • I'm guessing params[:q] and item.name are both strings, but they could be arrays. That needs to be clarified as well. Commented Sep 15, 2016 at 18:13

2 Answers 2

3
@items = items.select { |item| item.name.include?(params[:q]) }

Edit:

If you need the matching to be case insensitive.

@items = items.select { |item| item.name.downcase.include?(params[:q].downcase) }
Sign up to request clarification or add additional context in comments.

4 Comments

Is this case sensitive?
Yes, it is case sensitive.
Are you assuming item.name is a string or an array? That it's not item.names suggests it a string, but we can't be sure. Best to state your assumption with your answer, or, better, ask the OP for clarification.
Instances of String class also have method include? so you can test if string contains given substring. From the original code it is quite obvious that item.name is a string.
0

You can use a regexp:

pattern =  /#{params[:q]}/
@items = items.select { |item| pattern =~ item.name }

3 Comments

pattern #=> /out/ matches item.name #=> 'shouting'. If that's your intention, why did you interpret "as a LIKE" that way?
I'm not sure if I understand you. Regexp may be used for substring matchint just as LIKE, can't it? Btw. solution from accepted answer matches out in shouting as well: > 'shouting'.include? 'out' => true
Yes, but "as a LIKE" does not necessarily ask whether params[:q] is a substring of item.name (if it's a string or an array--we can't be sure). For all we know, params[:q] is "like" item.name if they are strings having the same numbers of characters. True, we can make inferences form the answer selected by the OP, but that was before you posted your answers, so it doesn't explain why you made the assumption you did. Moreover, many-a-time OPs have selected answers that don't do what they've asked or that are simply incorrect.

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.