Ruby- Adding/subtracting elements from one array with another array

subyman picture subyman · Apr 10, 2011 · Viewed 8.1k times · Source

I do this:

a = [1,2,3,4]  
b = [2,3,4,5]  
c = b - a  
put c 

I get this answer -> [1]
I want this answer -> [1,1,1,1] (like matrix addition/subtraction)

I tried this:

c.each {|e| c[e] = b[e] - a[e]}  

but I get this answer: [1,0,0,0]

Can someone give me a correct way to do this? Thanks a lot!

Answer

Todd Yandell picture Todd Yandell · Apr 10, 2011

You could use zip:

a.zip(b).map { |x, y| y - x }
# => [1, 1, 1, 1]

There is also a Matrix class:

require "matrix"

a = Matrix[[1, 2, 3, 4]]
b = Matrix[[2, 3, 4, 5]]
c = b - a
# => Matrix[[1, 1, 1, 1]]