2散列在这个顺序组合的最佳方式 [英] Best way to combine 2 hashes in this order

查看:147
本文介绍了2散列在这个顺序组合的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个散列list1的和列表2。密钥是用户ID。下面是一个例子。

I have 2 hashes list1 and list2. Keys are user ids. Here is an example

list1 = { '1' => [item1, item2],
          '2' => [item3]
        }

list2 = { '1' => [item 4],
          '3' => [item 5]
        }

我需要2到一个列表..这样的事情..或者什么更好的再presentation AP preciated结合起来。基本上,需要每个用户的list1的和列表2项合并为一个数组,其中第一个项目给我的list1的项目,第二个给我的列表2项。

I need to combine the 2 to one list.. something like this.. or any better representation appreciated. Basically, need each user's list1 and list2 items combined into one array where first item gives me the list1 items and second gives me the list2 items.

{ '1' => [[item 1, item 2], [item 4],
  '2' => [[item 3],[]],
  '3' => [[],[item 5]]
}

我能做到在一个老式的方法,但不知道是否有这样做一个最好的方式..想知道如果我能尽量减少code和处理。

I am able to do it in an old fashioned way, but wondering if there is a best way to do this.. wondering if I could minimize the code and processing.

推荐答案

这个输出是什么?

{ 
  '1' => [item 1, item 2, item 4],
  '2' => [item 3],
  '3' => [item 5]
}

您可以用得到它。

ret = list1.merge(list2){ |key, old, new| old + new }

这篇关于2散列在这个顺序组合的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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