views:

52

answers:

1

I have an array : a=[[1,2],[3]] and b=[[2,3],[5]] i need to add corresponding elements in each array simultaneously in order to obtain the result;

result=[[3,5],[8]].

Thanks and Cheers!

+4  A: 
a=[[1,2],[3]]
b=[[2,3],[5]]

def my_add a1, a2
  a1.zip(a2).map{|s1, s2|
    s1.is_a?(Array) ? my_add(s1, s2) : s1 + s2
  }
end

p my_add a, b
#=>[[3, 5], [8]]

But you have to be careful to always match an array with an array, and integer with an integer.

Mladen Jablanović