合并散列值的两个阵列,同时保持所有不同的值 [英] Merge two arrays of hashes whilst keeping all distinct values

查看:132
本文介绍了合并散列值的两个阵列,同时保持所有不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要散列值的两个数组合并成一个新的数组:

I want to merge two arrays of hashes into a new array:

array1 = [{"Name1" => {gender: 'female', nationality: ['german', 'danish']}}]
array2 = [{"Name1" => {gender: 'male', nationality: ['german', 'austrian']}}]

现在,这是我期待的结果:

Now this is the result I am looking for:

new_array = [{"Name1" => {gender: ['female', 'male'], nationality: ['german', 'danish', 'austrian']}}]

唯一合并选项我可以在Ruby文档中,可以找到将覆盖重复与其他哈希值。所以,我怎么能达到我需要的版本?

The only merge options I could find in the Ruby documentation would overwrite duplicates with the other hash. So how can I achieve the version I need?

推荐答案

您可以通过可选的块参数的 哈希#合并 。该块调用所复制的钥匙。在块的返回值被用于代替被覆盖。

You can pass optional block argument to Hash#merge. The block is invoked for the duplicated keys. in The return value of the block is used instead of being overwritten.

array1 = [{"Name1" => {gender: 'female', nationality: ['german', 'danish']}}]
array2 = [{"Name1" => {gender: 'male', nationality: ['german', 'austrian']}}]

new_array = [{'Name1' => array1[0]['Name1'].merge(array2[0]['Name1']) { |k,o,n|
  Array(o) | Array(n)
}}]
# => [{"Name1"=>
#       {:gender=>["female", "male"],
#        :nationality=>["german", "danish", "austrian"]}}]

这篇关于合并散列值的两个阵列,同时保持所有不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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