How can I sum array elements in place in ruby?

前端 未结 5 1391
面向向阳花
面向向阳花 2021-01-21 16:43

How can I create a new array for summing array elements in place in Ruby?

[1,2,3,4,5].each_cons(2).map {|a, b| a + b }

gives me [3, 5, 7,

5条回答
  •  醉话见心
    2021-01-21 17:36

    Another variation:

    > [1, 2, 3, 4, 5].reduce([]) {|acc, el| acc << el + (acc[-1] || 0); acc}
    #=> [1, 3, 6, 10, 15]
    

    Yuk.

提交回复
热议问题