tags:

views:

63

answers:

3

I have two arrays, each holding arrays with attribute hashes.

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 in the array is holding attribute hashes for an object. In the above example, there are two objects that I'm working with. There are two attributes in each array for each of the two objects.

How do I merge the two arrays? I am trying to get a single array of 'object' arrays (there is no way to get a single array from the start 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've tried a couple things, including the iteration methods and the merge method, but I've been unable to get the array I need.

A: 

There is no simple way to merge the hash tables.

You would need to create a new hash table large enough to hold all of the entries in the two previous arrays.

Then iterate over the two arrays and add each entry to the new hash table. This is since the size of the hash table is taken into account during the hashing procedure.

Nick
+1  A: 

I don't think my answer is valid anymore, since the question has been edited later.

Here, first I am fixing your array and hash notation in your question.

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"}]

You can simply concatenate the two arrays to get your desired array like so:

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"}]
nas
+3  A: 

You seem to have parallel arrays of hashes. We can use zip to turn the parallel arrays into a single array of arrays of hashes. We can then map each array of hashes into a single hash using inject and 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}]
Wayne Conrad
whoops. yes, that was a typo. thanks for the answer!
Ben
@Ben, You're welcome! I edited my answer to reflect your correction.
Wayne Conrad