给定一个类似于这样的Ruby哈希数组:
[{"lib1"=>"30"}, {"lib2"=>"30"}, {"lib9"=>"31"}, {"lib2"=>"31"}, {"lib3"=>"31"}, {"lib1"=>"32"}, {"lib2"=>"32"}, {"lib1"=>"33"}, {"lib3"=>"36"}, {"lib2"=>"36"}, {"lib1"=>"37"}]
我怎么得到这样的散列:
{"lib1"=>[30,32,33,37], lib2=>[30,31,32,36], lib3=>[31,36], lib9=>[31]}
最佳答案
a = [{"lib1"=>"30"}, {"lib2"=>"30"}, {"lib9"=>"31"}, {"lib2"=>"31"}, {"lib3"=>"31"}, {"lib1"=>"32"}, {"lib2"=>"32"}, {"lib1"=>"33"}, {"lib3"=>"36"}, {"lib2"=>"36"}, {"lib1"=>"37"}]
a.map(&:to_a).flatten(1).each_with_object({}) do |(k, v), h|
h[k] ||= []
h[k] << v
end
#=> {"lib1"=>["30", "32", "33", "37"],
# "lib2"=>["30", "31", "32", "36"],
# "lib9"=>["31"],
# "lib3"=>["31", "36"]}
可选地:
Hash[a.map(&:to_a).flatten(1).group_by(&:first).map { |k, v| [k, v.map(&:last)] }]
如果您愿意使用Facets,那么使用
collate
,这将变得非常简单:a.inject(:collate)