I have an array of integers, say
a=[4, 6, 7, 2] and I would like to produce a new array of the same size, with the following properties:
- The first array, b[0], is 0 - For the remaining elements, b[n] is the sum of all elements from a[0] up to a[n]. Hence, for a above, b should turn out as [0, 4, 10, 17].
Efficiency is not an issue (although I would like to reuse already caluclated partial sums, instead recalculate them again and again), but the result should be understandable in maintaiable.
I came up with the following solution:
b=[nil]*a.size ind=-1 b.map! {|i| (ind >= 0 ? (a[ind]+b[ind]) : 0).tap {ind+=1}}; This works, but I don't like it much, mostly because of the "backindex" variable ind and the need to preallocate b. I would like to have something like
b = a.map{ .... } or similar. Does anybody have some idea of how to do it better?
map.with_indexwhich moves that functionality to existing code.a.map_with_index {|i| ind=i-1;....}.ato, say,memoto avoid a warning that the local variableais shadowing the outer variablea(if$VERBOSEis turned on).