BC00
BC00

Reputation: 1639

Convert Ruby array of hashes into one hash

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

Answers (2)

Arup Rakshit
Arup Rakshit

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

Ismael
Ismael

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

Related Questions