How Do I Add Value To All Previous Values In Array
- by James
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.