合并哈希数组 [英] merging arrays of hashes

查看:130
本文介绍了合并哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个阵列,带属性散列双方各持股阵列。

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.

我如何合并两个数组?我试图让对象阵列的单个阵列(有没有办法让从一开始就单个阵列,因为我必须让两个不同的API调用来得到这些属性)。

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.

推荐答案

您似乎有散列的并行阵列。我们可以使用拉链打开并行阵列到哈希阵列的单个阵列。然后,我们可以哈希每个阵列使用映射到一个哈希合并

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

这篇关于合并哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆