Reputation: 1220
I have an array of Time
objects. I want my user to be able to select a subset of elements based on various criteria. The number of criteria is unknown and it can vary. Also, I would like to add additional criteria in the future if needed.
If ts
is the array, I can write:
ts.select{|t| (t.hour == 12 || t.hour == 16) && t.month == 3}
but how I could make this generic so that each method of Time
could potentially be used for filtering? For example, the UI could generate a Hash
:
{:hour => [12, 16], :month => [3]}
and this should be used to create the final filter combining all the conditions.
For each method I can have only OR
conditions and between methods only AND
conditions. For example the typical query would return all the time for Summer afternoons. So {:month => [6, 7, 8, 9], :hour => [12,13,14,15,16,17]}
Upvotes: 0
Views: 42
Reputation: 168199
{:hour => [12, 16], :month => [3]}
.inject(ts){|ts, (k, v)| ts.select{|t| v.include?(t.send(k))}}
Upvotes: 2