Find hash in another array and substract in Ruby -
i have 2 arrays of hashes this:
a = [ { car_id: 1, motor_id: 1, quantity: 5 }, { car_id: 1, motor_id: 2, quantity: 6 }, { car_id: 5, motor_id: 3, quantity: 3 } ] b = [ { car_id: 1, motor_id: 1, quantity: 2 }, { car_id: 1, motor_id: 2, quantity: 3 } ]
i want substract quantities each hash in b
hashes in a
hashes have same car_id
& motor_id
. so, expected result be:
c = [ {car_id: 1, motor_id: 1, quantity: 3}, {car_id: 1, motor_id: 2, quantity: 3}, {car_id: 5, motor_id: 3, quantity: 3 } ]
what way in ruby? thoughts iterate on a
, , each element find if there in b
have same car_id
, motor_id
, if so, substract, , continue.
i suggest first create hash bqty
b
that, each element (hash) g
of b
, maps [g[:car_id], g[:motor_id]]
g[:quantity]
:
bqty = b.each_with_object({}) {|g,h| h[[g[:car_id], g[:motor_id]]] = g[:quantity]} #=> {[1, 1]=>2, [1, 2]=>3}
next, map each element (hash) g
of a
desired hash. done merging g
empty hash h
(or g.dup
), then, if there element of bqty
key key = [h[:car_id], h[:motor_id]]
, subtract bqty[key]
h[:quantity]
. note leaves a
, b
unchanged.
a.map |g| {}.merge(g).tap |h| key = [h[:car_id], h[:motor_id]] h[:quantity] -= bqty[key] if bqty.key?(key) end end #=> [{:car_id=>1, :motor_id=>1, :quantity=>3}, # {:car_id=>1, :motor_id=>2, :quantity=>3}, # {:car_id=>5, :motor_id=>3, :quantity=>3}]
an alternative antepenultimate1 line is:
h[:quantity] -= bqty[key].to_i
since nil.to_i #=> 0
.
1. how can 1 pass opportunity use such word?
Comments
Post a Comment