How to add two multidimensional array in ruby

来源:互联网 发布:linux 字符串连接 编辑:程序博客网 时间:2024/05/25 08:13

I am working in a ruby on rails project where i am creating complex algorithm, i need help regarding adding 2 two dimensional array.i want to do following:

array1 = [[1,10],[2,20],[3,10],[4,30]]array2 = [[1,10],[2,10],[3,5],[4,10]]

I want to add two array in such a way like the second element of each array will be added not the first .i want the following output.

result = array1+array2result = [[1,20],[2,30],[3,15],[4,40]]

Thanks in advance!!

-----------------------------------------------------------------------------------------------------------------------------------

[array1, array2].transpose.map{|(k, v1), (_, v2)| [k, v1 + v2]}# => [[1, 20], [2, 30], [3, 15], [4, 40]]
array1 = [[1,10],[2,20],[3,10],[4,30]]array2 = [[1,10],[2,10],[3,5],[4,10]]Hash[array1].merge(Hash[array2]) { |key,old,new| old + new }.to_a# => [[1, 20], [2, 30], [3, 15], [4, 40]]

result = array1.zip(array2).map { |l, r| [l[0], l[1] + r[1]] }#=> [[1, 20], [2, 30], [3, 15], [4, 40]]

0 0
原创粉丝点击