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, 9] but expected result is [1,3,6,10,15].
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, 9] but expected result is [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!
.with_object(temporary_sum).arr.each_with_object(sum: 0).map! {|e, acc| acc[:sum] += e }in place means mutator. But I'll add your remark.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]
(sum + n).tap &y.method(:<<)[1, 2, 3, 4, 5].each_with_object([]){|e, a| a.push(a.last.to_i + e)}
# => [1, 3, 6, 10, 15]
to_i results in failing on, say, strings.#to_i is certainly there for the convention that nil.to_i returns 0. Aimed at numbers only.#+ defined on, I don’t see any reason to reject anything save for Numerics. a.push(a.last ? a.last + e : e) would work for anything.Another variation:
> [1, 2, 3, 4, 5].reduce([]) {|acc, el| acc << el + (acc[-1] || 0); acc}
#=> [1, 3, 6, 10, 15]
Yuk.
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]