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 su
@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
[[0, 0, 0], [2, 2, 1], [1,3,4]].transpose.map {|a| a.inject(:+)}
=> [3, 5, 5]
[[1,2,3],[4,5,6]].transpose.map {|a| a.inject(:+)}
=> [5, 7, 9]
here's my attempt at code-golfing this thing:
// ruby 1.9 syntax, too bad they didn't add a sum() function afaik
[1,2,3].zip([4,5,6]).map {|a| a.inject(:+)} # [5,7,9]
zip
returns [1,4]
, [2,5]
, [3,6]
, and map sums each sub-array.
This might not be the best answer but it works.
array_one = [1,2,3]
array_two = [4,5,6]
x = 0
array_three = []
while x < array_one.length
array_three[x] = array_one[x] + array_two[x]
x += 1
end
=>[5,7,9]
This might be more lines of code than other answers, but it is an answer nonetheless
[[1,2,3],[4,5,6]].transpose.map{|a| a.sum} #=> [5,7,9]
For:
a = [1,2,3]
b = [4,5,6]
You could zip
and then use reduce
:
p a.zip(b).map{|v| v.reduce(:+) }
#=> [5, 7, 9]
Or, if you're sure that array a
and b
will always be of equal length:
p a.map.with_index { |v, i| v + b[i] }
#=> [5, 7, 9]
Here's the transpose
version Anurag suggested:
[[1,2,3], [4,5,6]].transpose.map {|x| x.reduce(:+)}
This will work with any number of component arrays. reduce
and inject
are synonyms, but reduce
seems to me to more clearly communicate the code's intent here...