I have the following two Ruby arrays which each are made up of hashes:
arr1 = [{:a=>"6884", :b=>true}, {:a=>"8456", :b=>false}, {:a=>"5631", :b=>false}]
arr2 = [{:c=>"6884"}, {:c=>"8023"}, {:c=>"9837"}]
I want to merge each hash of arr2
into each hash of arr1
that is at the same index. So the final array would look like:
arr3 = [{:a=>"6884", :b=>true, :c=>"6884"}, {:a=>"8456", :b=>false, :c=>"8023"}, {:a=>"5631", :b=>false, :c=>"9837"}]
I am sure there is a nice Ruby way of doing this, but I haven't quite figured it out. Any help would be greatly appreciated.
CodePudding user response:
Input
arr1 = [{ :a => "6884", :b => true }, { :a => "8456", :b => false }, { :a => "5631", :b => false }]
arr2 = [{ :c => "6884" }, { :c => "8023" }, { :c => "9837" }]
Code
p arr1.zip(arr2).map { |h1, h2| h1.merge(h2) }
Output
[{:a=>"6884", :b=>true, :c=>"6884"}, {:a=>"8456", :b=>false, :c=>"8023"}, {:a=>"5631", :b=>false, :c=>"9837"}]
CodePudding user response:
Another way:
arr1.each_index.map { |i| arr1[i].merge(arr2[i]) }
#=> [{:a=>"6884", :b=>true, :c=>"6884"},
# {:a=>"8456", :b=>false, :c=>"8023"},
# {:a=>"5631", :b=>false, :c=>"9837"}]
This avoids the creation of the temporary array arr1.zip(arr2)
, but it should only be considered (to save memory) if the arrays are quite large, as it has the disadvantage that if does not read as well as answers employing arr1.zip(arr2)
(or [arr1, arr2].transpose
).
Note that, without a block, Array#each_index returns an enumerator.
CodePudding user response:
try this:
arr1 = [{:a=>"6884", :b=>true}, {:a=>"8456", :b=>false}, {:a=>"5631", :b=>false}]
arr2 = [{:c=>"6884"}, {:c=>"8023"}, {:c=>"9837"}]
arr1.zip(arr2).map{|a| a[0].merge(a[1])}