How can I create a new array for summing array elements in place in Ruby?
[1,2,3,4,5].each_cons(2).map {|a, b| a + b }
gives me [3, 5, 7,
[1, 2, 3, 4, 5].each_with_object([]){|e, a| a.push(a.last.to_i + e)}
# => [1, 3, 6, 10, 15]
Another variation:
> [1, 2, 3, 4, 5].reduce([]) {|acc, el| acc << el + (acc[-1] || 0); acc}
#=> [1, 3, 6, 10, 15]
Yuk.
Lots of ways to do this. One way is to create an Enumerator
instance and use inject
:
def adder array
enum = Enumerator.new do |y|
array.inject (0) do |sum, n|
y << sum + n
sum + n
end
end
enum.take array.size
end
adder [1,2,3,4,5] #=> [1, 3, 6, 10, 15]
More simple for understanding, I think:
temp_sum = 0
arr.map! {|e| temp_sum += e }
=> [1, 3, 6, 10, 15]
If you want to create a new array instead of existing one, just use map
instead of map!
It's not very elegant, but it seems to work :
[1,2,3,4,5].each_with_object([]){|i,l| l<<(l.last||0)+i}
#=> [1,3,6,10,15]