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?
@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) }
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.include? so you can test if string contains given substring. From the original code it is quite obvious that item.name is a string.You can use a regexp:
pattern = /#{params[:q]}/
@items = items.select { |item| pattern =~ item.name }
pattern #=> /out/ matches item.name #=> 'shouting'. If that's your intention, why did you interpret "as a LIKE" that way?> 'shouting'.include? 'out' => trueparams[: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.
params[:q]anditem.nameare both strings, but they could be arrays. That needs to be clarified as well.