Adding array elements in ruby

I have this array:

a1 = [1,2,3,4] 

I want to generate this array from a1 :

 a2 = [3, 5, 7] 

The formula is [a1[0] + a1[1], a1[1] + a1[2], ...] .

What is the Ruby way to do this?

+8
ruby
source share
1 answer

Yes, you can do it as below:

 a1 = [1,2,3,4] a2 = a1.each_cons(2).map{ |a| a.inject(:+) } #=> [3, 5, 7] 
+14
source share

All Articles