Reputation: 2357
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
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