macsig macsig - 1 month ago 21
Ruby Question

Merging an array of hashes

I have the following array:

x = [ { a: [1,2] }, { a: [3,4] }, { a: [5,6] } ]


and I need to get

{ a: [[1,2], [3,4], [5,6]] }


I have tried to use (among other options)
merge
:

x.each_with_object({}) do |a, b|
b.merge!(a) {|k, o, n| o.zip(n) }
end


But unfortunately, I get an extra array around the result.

Any suggestions?

THANKS

Answer
x.flat_map(&:to_a).group_by(&:first).map{ |k, v| [k, v.map(&:last)] }.to_h
#=> [{:a=>[[1, 2], [3, 4], [5, 6]]}]