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.
For:
You could
zip
and then usereduce
:Or, if you're sure that array
a
andb
will always be of equal length:I humbly feel that the other answers I see are so complex that they would be confusing to code reviewers. You would need to add an explanatory comment, which just increases the amount of text needed.
How bout this instead:
Slightly different solution: (so that you're not hard coding the "2")
Finally, mathematically speaking, this is the same question as this:
How do I perform vector addition in Ruby?
Now we can use sum in 2.4