Best way to combine 2 hashes in this order

2019-08-05 09:41发布

问题:

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

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

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:

What about this output?

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

You could get it with

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