ruby: sum corresponding members of two or more arrays

前端 未结 9 798
孤独总比滥情好
孤独总比滥情好 2020-12-13 09:01

I\'ve got two (or more) arrays with 12 integers in each (corresponding to values for each month). All I want is to add them together so that I\'ve got a single array with su

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 09:35

    @FriendFX, you are correct about @user2061694 answer. It only worked in Rails environment for me. You can make it run in plain Ruby if you make the following changes...

    In the IRB

    [[0, 0, 0], [2, 2, 1], [1,3,4]].transpose.map {|a| a.inject(:+)}
     => [3, 5, 5]
    
    
    [[1,2,3],[4,5,6]].transpose.map {|a| a.inject(:+)}
     => [5, 7, 9]
    

提交回复
热议问题