2

I have an array like this:

array = [[val1, val2, val3], [val1, val2, val3], [val1, val2, val3]]

I am trying to do:

[[val1+val1+val1], [val2+val2+val2], [val3+val3+val3]

I am trying to find a Ruby method that makes it more easy and less messy.

1 Answer 1

5

Transpose the array using Array#transpose, then use Enumerable#map to get sum of each row:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array.transpose.map { |a| a.inject :+ }
# => [12, 15, 18]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.