SupremeA SupremeA - 2 months ago 16
Ruby Question

Subtract one array of arrays from another ruby

I have an array of months and amounts like so...

a = [[9, 2336.02], [8, 7993.6], [7, 5265.73], [6, 7075.33], [5, 9281.02], [4, 9524.64], [3, 300]]


I then have another like so...

b = [[9, 2817.61], [8, 7033.74], [7, 5650.73], [6, 9206.72], [5, 8554.24], [4, 6682.1], [3, 2211.84]]


I need to subtract the amounts in array a from the amounts in array b while keeping the keys. So my output should look like

c = [[9,-481.59], [8, 959.86],[...]]


I tried

a.each_with_index.map { |month, amount| amount - b.each { |months,cost| cost }


But can't seem to get it right. I would appreciate any help.

Answer

you can use zip

c = a.zip(b).map{|k| [k[0][0], (k[0][1] - k[1][1]).round(2)] }
#=> [[9, -481.59], [8, 959.86], [7, -385.0], [6, -2131.39], [5, 726.78], [4, 2842.54], [3, -1911.84]]