简体   繁体   中英

How to combine two hashes with same keys into a 2D array in Ruby

I have two hashes of values by date:

 a = {1=>4, 2=>5, 3=>10}
 b = {1=>43, 2=>25, 3=>28}

How would I combine them in Ruby into a 2D array like this:

 c = [[1, 4, 43], [2, 5, 25], [3, 10, 28]]

Just use Enumerable#map :

a.map { |k, v| [k, v, b[k]] }
#=> [[1, 4, 43], [2, 5, 25], [3, 10, 28]]

Or, if you have different keys in your hashes, use Hash#merge :

a.merge(b) { |_, o, n| [o, n] }.map { |k, v| [k, *v] }
#=> [[1, 4, 43], [2, 5, 25], [3, 10, 28]]

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