Merging hash arrays

I have two arrays, each of which contains arrays of attributes.

Array1 => [[{attribute_1 = A}, {attribute_2 = B}], [{attribute_1 = A}, {attribute_4 = B}]]
Array2 => [{attribute_3 = C}, {attribute_2 = D}], [{attribute_3 = C, attribute_4 = D}]]

Each array of the array contains attribute hashes for the object. In the above example, there are two objects that I work with. Each array has two attributes for each of the two objects.

How to combine two arrays? I am trying to get one array of arrays of “objects” (there is no way to get one array from the very beginning, because I have to make two different API calls to get these attributes).

DesiredArray => [[{attribute_1 = A, attribute_2 = B, attribute_3 = C, attribute_4 = D}],
                 [{attribute_1 = A, attribute_2 = B, attribute_3 = C, attribute_4 = D}]]

I tried a couple of things, including iteration methods and a merge method, but I was not able to get the array I need.

+1
source share
2 answers

, , . zip, . inject merge:

#!/usr/bin/ruby1.8

require 'pp'

array1 = [{:attribute_1 => :A, :attribute_2 => :B}, {:attribute_1 => :A, :attribute_4 => :B}]
array2 = [{:attribute_3 => :C, :attribute_2 => :D}, {:attribute_3 => :C, :attribute_4 => :D}]

pp array1.zip(array2).collect { |array| array.inject(&:merge) }
# => [{:attribute_2=>:D, :attribute_1=>:A, :attribute_3=>:C},
# =>  {:attribute_4=>:D, :attribute_1=>:A, :attribute_3=>:C}]
+5

, , .

, - .

Array1 = [{'attribute_1' => 'A', 'attribute_2' => 'B'}, {'attribute_1' => 'A', 'attribute_2' => 'B'}]
#=> [{"attribute_1"=>"A", "attribute_2"=>"B"}, {"attribute_1"=>"A", "attribute_2"=>"B"}]
Array2 = [{'attribute_3' => 'C', 'attribute_2' => 'D'}, {'attribute_3' => 'C', 'attribute_4' => 'D'}]
#=> [{"attribute_2"=>"D", "attribute_3"=>"C"}, {"attribute_3"=>"C", "attribute_4"=>"D"}]

, :

DesiredArray = Array1+Array2
# => [{"attribute_1"=>"A", "attribute_2"=>"B"}, {"attribute_1"=>"A", "attribute_2"=>"B", {"attribute_2"=>"D", "attribute_3"=>"C"}, {"attribute_3"=>"C", "attribute_4"=>"D"}]
+1

All Articles