Cameron
Cameron

Reputation: 28803

Ruby select from array where key is like parameter

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?

Upvotes: 2

Views: 1805

Answers (2)

jan.zikan
jan.zikan

Reputation: 1316

@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) }

Upvotes: 3

mrzasa
mrzasa

Reputation: 23327

You can use a regexp:

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

Upvotes: 0

Related Questions