ruby - How do I add a cumulative sum to an array for only one value? -


i have array of arrays x , y values:

[[some_date1, 1], [some_date2, 3], [some_date3, 5], [some_date4, 7]] 

the result should sum y values (1, 3, 5, 7) result this:

[[some_date1, 1], [some_date2, 4], [some_date3, 9], [some_date4, 16]] 

how possible in ruby?

yes, possible in ruby. can use [map][1] , this:

sum = 0 array.map {|x,y| [x, (sum+=y)]} 

this how works. given input:

array = ["one", 1], ["two", 2] 

it iterate through each of elements in array e.g.) first element ["one", 1].

it take element (which array itself) , assign variable x first element in array e.g.) "one" , y second e.g.) 1.

finally, return array result this:

=> ["one", 1], ["two", 3] 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -