[英]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: 我如何将它们在Ruby中组合成这样的2D数组:
c = [[1, 4, 43], [2, 5, 25], [3, 10, 28]]
Just use Enumerable#map
: 只需使用
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
: 或者,如果您的哈希中有不同的密钥,请使用
Hash#merge
:
a.merge(b) { |_, o, n| [o, n] }.map { |k, v| [k, *v] }
#=> [[1, 4, 43], [2, 5, 25], [3, 10, 28]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.