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.
@FriendFX, you are correct about @user2061694 answer. It only worked in Rails environment for me. You can make it run in plain Ruby if you make the following changes...
In the IRB
This might not be the best answer but it works.
This might be more lines of code than other answers, but it is an answer nonetheless
here's my attempt at code-golfing this thing:
zip
returns[1,4]
,[2,5]
,[3,6]
, and map sums each sub-array.For clearer syntax (not the fastest), you can make use of
Vector
:For multiple vectors, you can do:
If you wish to load your arrays into Vectors and sum:
Here's the
transpose
version Anurag suggested:This will work with any number of component arrays.
reduce
andinject
are synonyms, butreduce
seems to me to more clearly communicate the code's intent here...