ruby: sum corresponding members of two or more arrays

前端 未结 9 761
孤独总比滥情好
孤独总比滥情好 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:49

    Here's the transpose version Anurag suggested:

    [[1,2,3], [4,5,6]].transpose.map {|x| x.reduce(:+)}
    

    This will work with any number of component arrays. reduce and inject are synonyms, but reduce seems to me to more clearly communicate the code's intent here...

提交回复
热议问题