Home > Blockchain >  Merging two arrays of hashes in Ruby
Merging two arrays of hashes in Ruby

Time:07-15

I’m very close to solving a project I’ve been working on for a while but can’t seem to figure this out.

array1 = [{:new_listing => "1", :item => "apple"}, {:new_listing => "2", :item => "bannana"}]
array2 = [{:height => "10"}, {:height => "12"}]

How do I merge them so it is

[{:new_listing => "1", :item => "apple", :height => "10" },
 {:new_listing => "2", :item => "bannana", :height => "12"}]

The order of each arrays are aligned, and should be the same size. Some values of array2 will be {:height => nil}.

CodePudding user response:

The order of each arrays are aligned, and should be the same size.

That's exactly the description of the zip method.

zip(arg, ...) → an_array_of_array

Takes one element from enum and merges corresponding elements from each args.

Likewise, merging hashes is done with merge

array1.zip(array2).map { |x, y| x.merge(y) }

CodePudding user response:

array1.map {|x| x.merge!(array2.shift) }

use map/each as per your requirement

CodePudding user response:

Below solution should work for you:

array1 = [{:new_listing=> "1", :item=> "apple"}, {:new_listing=> "2", :item=> "bannana"}]
array2 = [{:height=> "10"},{:height => "12"}]

array2.each_with_index { |hash, index| array1[index] = array1[index].merge(hash) }

puts array1
# [{:new_listing=>"1", :item=>"apple", :height=>"10"}, {:new_listing=>"2", :item=>"bannana", :height=>"12"}]
  •  Tags:  
  • ruby
  • Related