How can I sum array elements in place in ruby?

前端 未结 5 1390
面向向阳花
面向向阳花 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]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-21 17:39

    Lots of ways to do this. One way is to create an Enumerator instance and use inject:

    def adder array
      enum = Enumerator.new do |y|
        array.inject (0) do |sum, n|
          y << sum + n
          sum + n
        end
      end
      enum.take array.size
    end
    
    adder [1,2,3,4,5] #=> [1, 3, 6, 10, 15]
    
    0 讨论(0)
  • 2021-01-21 17:42

    More simple for understanding, I think:

    temp_sum = 0
    arr.map! {|e| temp_sum += e }
    => [1, 3, 6, 10, 15]
    

    If you want to create a new array instead of existing one, just use map instead of map!

    0 讨论(0)
  • It's not very elegant, but it seems to work :

    [1,2,3,4,5].each_with_object([]){|i,l| l<<(l.last||0)+i}
    #=> [1,3,6,10,15]
    
    0 讨论(0)
提交回复
热议问题