What is the clearest way to add all the elements in a two-dimensional array by position using Ruby?

advertisements

What is the clearest and most efficient way to add all the elements in 2D array by their position in Ruby. Example:

2darray = [[1,2,3],[1,2,3]]
result = [2,4,6]

I have the following code

def sum_elements_by_position(array)
 total_elements = array.length
 result = []

 for i in 0...array.first.length
   n = 0
   array.each { |subarray| n += subarray[i] }
   result << n
 end
 result
end

Assumptions: All primary elements are of the same length

For bonus points it would be great to see a solution that works primary elements of an arbitrary length


You can zip the first row with the rest of them and then do the sum:

def sum_elements_by_position(array)
    array[0].zip(*array[1..-1]).map do |col|
        col.inject(:+)
    end
end