user user - 6 months ago 64
Ruby Question

Rails merge two array of hashes

I have two arrays of hashes and want to do one from it

first =
[{:frontman=>"aaa", :category=>"bbb", :subcategory=>nil, :detail=>nil},other hashes]


second =
[{:__content__=>"aaa", :id=>"9096290", :frontman=>"aaa"},other hashes]


I want to have

one large array of hashes

[{:__content__=>"aaa", :id=>"9096290", :frontman=>"aaa", :category=>"bbb", :subcategory=>nil, :detail=>nil},other hashes]


i have tried it

(first+second).group_by{|h| h[:frontman]}.map{|k,v| v.reduce(:merge)}


but it doesn't work for me

Answer

You can use this way:

first.zip(second).map { |f, s| f.merge(s) }
#=> [{:frontman=>"aaa", :category=>"bbb", :subcategory=>nil, ...}]