ruby: sum corresponding members of two or more arrays

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

    For:

    a = [1,2,3]
    b = [4,5,6]
    

    You could zip and then use reduce:

    p a.zip(b).map{|v| v.reduce(:+) }
    #=> [5, 7, 9]
    

    Or, if you're sure that array a and b will always be of equal length:

    p a.map.with_index { |v, i| v + b[i] }
    #=> [5, 7, 9]
    

提交回复
热议问题