Bloomberg
Bloomberg

Reputation: 2357

how to add multiple arrays in an array like this in ruby

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.

Upvotes: 2

Views: 110

Answers (1)

falsetru
falsetru

Reputation: 368944

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]

Upvotes: 5

Related Questions