Reputation: 1639
I have the following array:
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
I want to convert it into 1 big hash but keep all of the values, so I want it to look like the following:
{"a" => [2, nil], "b" => [3, nil], "c" => [2]}
I can get close doing array.inject({}) {|s, h| s.merge(h)}}
, but it overwrites the values.
Upvotes: 0
Views: 752
Reputation: 118261
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
a = array.each_with_object(Hash.new([])) do |h1,h|
h1.each{|k,v| h[k] = h[k] + [v]}
end
a # => {"a"=>[2, nil], "b"=>[3, nil], "c"=>[2]}
Upvotes: 2
Reputation: 16720
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
res = {}
array.each do |hash|
hash.each do |k, v|
res[k] ||= []
res[k] << v
end
end
Upvotes: 0