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
- How to add two multidimensional array in ruby
- Ruby: Multidimensional array to multidimensional hash
- String to array to multidimensional hash in ruby
- How to gsub \ in ruby array?
- How to create this array in Ruby?
- How to format strings in an array in ruby?
- ruby remove duplicates from multidimensional array
- how to sort array in ruby if i have nil object inside array?
- how to remove nil and blank string in an array in Ruby
- How to sort an array in Ruby to a particular order?
- How to find number of a specific integer in an array of Fixnums ruby
- how to merge array of hash based same keys in ruby?
- How to get array from string contained identical symbols in Ruby?
- How to get array from string contained identical symbols in Ruby?
- Appending to JSON array in Ruby
- How to add swap space in Linux
- How to add Snap-in (扩展Powershell)
- How to add new partition in centos
- Ubuntu下编译基于libpoco工程详解
- MySQL学习笔记之三 表类型
- curl常用操作集锦
- Java实现仿百度文库文档在线阅读
- Swift中文教程(二)基本运算符
- How to add two multidimensional array in ruby
- 阿里巴巴、亚马逊线上开战 紧盯马来西亚商场
- Java Thread join() 的用法
- Swift中文教程(三) 字符串和字符
- ThinkPHP的controller里变量输出位置不正确导致变量输出无效,原因不明??
- 掩模的概念
- 黑马程序员-IO(2)
- socket之select模型中各函数杂谈
- Mysql Union实例