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

I'm doing it:

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

I get this answer → [1]
I want to get this answer → [1,1,1,1] (for example, 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 the correct way to do this? Many thanks!

+6
source share
2 answers

You can 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]] 
+16
source

You can use each_with_index and map .

  c = b.each_with_index.map { |n,i| n - a[i] } # => [1, 1, 1, 1] 
+2
source

Source: https://habr.com/ru/post/885592/


All Articles