简体   繁体   中英

Best way to combine 2 hashes in this order

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.

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 }

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