3

I can't seem to find a way to add two arrays together. For instance is there a way to add a = [1,2,3] b = [4,5,6] to get the result c = [5,7,9]

1
  • What happens when one array has more elements than the other? Commented Sep 25, 2012 at 14:03

3 Answers 3

8

I don't have better than this : c = a.zip(b).map { |x, y| x + y }

Assuming your arrays have the same size.

Sign up to request clarification or add additional context in comments.

Comments

7

The problem is when the arrays aren't the same sizes:

a = [1,2]
b = [4,5,6]
ary = a.map.with_index{ |m,i| m + b[i].to_i }
=> [5, 7]

a = [1,2,3]
b = [4,5]
ary = a.map.with_index{ |m,i| m + b[i].to_i }
=> [5, 7, 3]

If the second array is shorter it works. If the first array is shorter it truncates the length of the resulting array to fit. That might not be what you want.

a = [1,2,3]
b = [4,5,6]
ary = a.map.with_index{ |m,i| m + b[i].to_i }
=> [5, 7, 9]

Fixing the problem with the array-lengths changes things a little. I'd do this:

a = [1,2,3]
b = [4,5]
ary = a.zip(b).each_with_object([]){ |( a,b ), m| m << a + b.to_i }
=> [5, 7, 3]

Comments

0

Another option for same length arrays:

[a,b].transpose.map{|x| x.reduce :+}

Especially useful when adding multiple arrays:

[a,b,c,d,e].transpose.map{|x| x.reduce :+}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.