From: Robert Klemme Date: 2009-04-06T17:14:29+09:00 Subject: Re: how to dynamically create search term for array.find_all On 06.04.2009 03:13, Adam Akhtar wrote: > i want to be able to create a mehtod that will filter results in an > array. The conditions are known at run time so id like to be able to do > it on the fly / dynamically. > > e.g. user wants to filter results in array so that only results which > have the following categories are returned > > :scifi > :comedy > :horror > > id like that to be placed into a Array.find_all call like below > > > some_array.find_by {|x| x.category == :scifi OR x.category == :horror OR > x.category == :comedy} > > how do i write the {....} bit if i dont know in advance exactly how many > / which cateogries will be requested? > > I know i could take hte users selections and put them in an array and do > this > > filtered_results = [] > > users_filter_choices.each do |filter| > filtered_results += all_results.find_all{|x| x.category == filter > end > > i dont know but is that bad for performance? Could be because you traverse the array multiple times. IMHO it is generally better to do that only once, e.g. require 'set' ufc = users_filter_choices.to_set all_results.find_all {|x| ufc.include?( x.category )} > Also it assumes that the conditions must == , what happens if i want > less than or more thans in there for numerical attributes? It really depends on the condition. I mean you not only have to define numbers but also which relation you want to evaluate. Cheers robert