Search code examples
rubyarraysiterationarraycollection

How Do I Add Value To All Previous Values In Array


Lets say I have the following array:

my_array = [1, 5, 8, 11, -6]

I need to iterate over this array and add the values prior to the current value together. An example will probably be easier to understand. I need to return an array that should look something like this:

final_array = [1, 6, 14, 25, 19]

I have tried doing something like this:

my_array.collect {|value| value + previous_values }

But obviously that doesn't work because I can't figure out how to get the previous values in the array.

I am a programming noob so this might be easier than I am making it. I am pretty sure I need to use either collect or inject, but I can't seem to figure out how to do this.

Any help would be appreciated.


Solution

  • Your own attempt at it with collect was already very close; just keep summing the previous values as you go.

    my_array = [1, 5, 8, 11, -6]
    previous_values = 0
    my_array.collect { |value| previous_values += value }
    # => [1, 6, 14, 25, 19]