Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting Values in two identical hashes in ruby

Tags:

ruby

hash

I have two hashes that are identical in structure...

hash1 = {:total=>{:gold=>100, :dark=>500}, :defensive=>{:gold=>100, :dark=>500}}
hash2 = {:total=>{:gold=>20, :dark=>200}, :defensive=>{:gold=>20, :dark=>200}}

I want to subtract and return the following result...

hash1 - hash2 => {:total=>{:gold=>80, :dark=>300}, :defensive=>{:gold=>80, :dark=>300}}

Maybe this type of operation is not recommended. I'd appreciate that feedback as well. :-)

like image 513
thedanotto Avatar asked Jun 25 '26 16:06

thedanotto


1 Answers

I would just do:

hash1 = {:total=>{:gold=>100, :dark=>500}, :defensive=>{:gold=>100, :dark=>500}}
hash2 = {:total=>{:gold=>20, :dark=>200}, :defensive=>{:gold=>20, :dark=>200}}

hash1.merge(hash2) { |_, l, r| l.merge(r) { |_, x, y| x - y } }
#=> {:total=>{:gold=>80, :dark=>300}, :defensive=>{:gold=>80, :dark=>300}}
like image 128
spickermann Avatar answered Jun 28 '26 09:06

spickermann