DoLoveSky
DoLoveSky

Reputation: 777

Array element additions 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?

Upvotes: 7

Views: 208

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Yes, you can do this as below:

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

Upvotes: 14

Related Questions