Filtering Ruby array of hashes by another hash
Perhaps I am missing something obvious. It seems difficult to filter the hash with another hash or multiple key / value pairs.
fruit = [
{ name: "apple", color: "red", pieable: true },
{ name: "orange", color: "orange", pieable: false },
{ name: "grape", color: "purple", pieable: false },
{ name: "cherry", color: "red", pieable: true },
{ name: "banana", color: "yellow", pieable: true },
{ name: "tomato", color: "red", pieable: false }
]
filter = { color: "red", pieable: true }
# some awesome one-liner? would return
[
{ name: "apple", color: "red", pieable: true },
{ name: "cherry", color: "red", pieable: true }
]
An array of hashes that I don't think of is the problem. I don't even know how to check the hash with another arbitrary hash. I am using Rails, so nothing from active_support etc. OK.
+3
source to share
6 answers
I would tend to use Enumerable # group_by for this:
fruit.group_by { |g| { color: g[:color], pieable: g[:pieable] } }[filter]
#=> [{:name=>"apple", :color=>"red", :pieable=>true},
# {:name=>"cherry", :color=>"red", :pieable=>true}]
+1
source to share
Tony Arieri (@bascule) gave this really nice solution on twitter.
require 'active_support/core_ext' # unneeded if you are in a rails app
fruit.select { |hash| hash.slice(*filter.keys) == filter }
And it works.
# [{:name=>"apple", :color=>"red", :pieable=>true},
# {:name=>"cherry", :color=>"red", :pieable=>true}]
0
source to share