Array element additions in ruby -
i have array:
a1 = [1,2,3,4]
i want generate array a1
:
a2 = [3, 5, 7]
the formula [a1[0] + a1[1], a1[1] + a1[2], ...]
.
what ruby way this?
yes, can below:
a1 = [1,2,3,4] a2 = a1.each_cons(2).map{ |a| a.inject(:+) } #=> [3, 5, 7]
Comments
Post a Comment