简体   繁体   中英

Rails: Grouping Hashes with same date and getting their difference

I have 2 hases:

x = {Sun, 01 Oct 2017=>10, Wed, 01 Nov 2017=>4, Fri, 01 Dec 2017=>2}

y = {Sun, 01 Oct 2017=>7, Wed, 01 Nov 2017=>2, Fri, 01 Dec 2017=>1}

I wanted to group them and get their difference, which should produce this result:

z = {Sun, 01 Oct 2017=>3, Wed, 01 Nov 2017=>2, Fri, 01 Dec 2017=>1}

You can use reduce to achieve this, as follows:

z = x.reduce({}) do |z_hash, (key, val)|
  next z_hash unless y[key]
  z_hash[key] = val - y[key]
  z_hash
end

Alternatively, and more built to purpose, you could use:

z = x.merge(y) { |key, v1, v2| v1 - v2 }

The first approach allows you to easily skip keys that don't appear in both hashes, while the second is what I'd recommend - merge takes an optional block for cases like this.

It's readable and gets exactly the output you'd expect.

Hope that helps - give me a shout if you've any questions :)

ar = x , y z = p ar.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v - new_v}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM