Amal
Amal

Reputation: 222

How to subtract values from one array with another ruby

I have an array like below and I want to subtract one set from another set.

values1 = [[6336.94, 0, 0, 0], [3613.12, 0, 0, 0], [2862.95, 0, 0, 0]]


values2 = [[-842.68, 0, 0, 0], [-184.25, 0, 0, 0], [-112.18, 0, 0, 0]]

I want to get a final array like this:

[[7179.62,0,0,0],[3797.37,0,0,0],[2975.13,0,0,0]]

I have tried values1.zip(values2).map {|x,y| x-y} but it returns me with an array with first one and zero's removed.

Upvotes: 1

Views: 1306

Answers (1)

Siim Liiser
Siim Liiser

Reputation: 4348

.zip only looks one level down. In your example x and y are not the values in the internal arrays, they're the internal arrays themselves. Subtracting one array from another removes all common elements from the first. That's why the result you see is first array with all zeros (common elements) removed.

If you want to zip the internal arrays, you need to go one level deeper:

values1.zip(values2).map { |x, y| x.zip(y).map { |a, b| a - b } }

Upvotes: 5

Related Questions