Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two arrays into another array [duplicate]

Tags:

arrays

ruby

Possible Duplicate:
ruby: sum corresponding members of two arrays

So I'm struggling to do this.

I am trying to add two arrays and put the results into a third one. Now I want to be able to do this through a function though.

So I have Array_One, Array_Two, and Array_Three. I would want to call the "compare function" to one and two and make Three that length and then if they the lengths matched I would want to add One and Two and put the results in three.

Could this be done in one function? Better way to do this? That's my thought process but I don't have the knowledge of Ruby to do this.

EDIT: Sorry for the vagueness.

Array_One = [3,4]
Array_Two = [1,3]
Array_Three= []

I would want to pass One and Two through a function that compares the length and verifies they're the same length. Then I would, in my mind, send it through a function that actually does the adding. So in the end I would have Array_Three = [4,7] Hope that helps.


1 Answers

Your question's description is little confusing, but I think this may be what you want:

def add_array(a,b)
  a.zip(b).map{|pair| pair.reduce(&:+) }
end

irb> add_array([1,2,3],[4,5,6])
=> [5, 7, 9]

In addition it generalize to add multiple arrays quite easily:

def add_arrays(first_ary, *other_arys)
  first_ary.zip(*other_arys).map{|column| column.reduce(&:+) }
end

irb> add_arrays([1,2,3],[4,5,6])
=> [5, 7, 9]
irb> add_arrays([1,2,3],[4,5,6],[7,8,9])
=> [12, 15, 18]
like image 175
dbenhur Avatar answered May 06 '26 06:05

dbenhur