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]
3 Answers
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]