简体   繁体   中英

Ruby merge two arrays of hashes

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM