How can I sum array elements in place in ruby?

前端 未结 5 1389
面向向阳花
面向向阳花 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:33

    [1, 2, 3, 4, 5].each_with_object([]){|e, a| a.push(a.last.to_i + e)}
    # => [1, 3, 6, 10, 15]
    

提交回复
热议问题