ruby: sum corresponding members of two arrays
        Posted  
        
            by jjnevis
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by jjnevis
        
        
        
        Published on 2010-04-21T11:25:15Z
        Indexed on 
            2010/04/21
            11:43 UTC
        
        
        Read the original article
        Hit count: 203
        
I've got two (or more) arrays with 12 integers in each (corresponding to values for each month). All I want is to add them together so that I've got a single array with summed values for each month. Here's an example with three values: [1,2,3] and [4,5,6] => [5,7,9]
The best I could come up with was:
[[1,2,3],[4,5,6]].transpose.map{|arr| arr.inject{|sum, element| sum+element}} #=> [5,7,9]
Is there a better way of doing this? It just seems such a basic thing to want to do.
© Stack Overflow or respective owner