How Do I Add Value To All Previous Values In Array

Posted by James on Stack Overflow See other posts from Stack Overflow or by James
Published on 2010-05-17T07:59:38Z Indexed on 2010/05/17 8:20 UTC
Read the original article Hit count: 259

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about arrays