numbers = [
[1,2,3],
[4,5,6],
[7,8,9]
]
I was thinking of a method to get the following array by adding the same indexes from such an array.
sums = [12, 15, 18]
numbers = [[1,2,3], [4,5,6], [7,8,9]]
sums = numbers.transpose.map{ |num| num.sum }
is.
At first, I was thinking about the nested "how to get the 0th of the array", and I was worried about the efficient acquisition method. However, if you think of it as a matrix and transpose it, it was one shot.
Matrix transpose is possible with transpose
in Ruby. Reference: instance method Array # transpose
Recommended Posts