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
Post a Comment