7

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?

1 Answer 1

14

Yes, you can do this as below:

a1 = [1,2,3,4]
a2 = a1.each_cons(2).map{ |a| a.inject(:+) } #=> [3, 5, 7] 
Sign up to request clarification or add additional context in comments.

1 Comment

The second line could also be a2 = a1.each_cons(2).map{ |a,b| a + b } which I find a bit easier to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.