If you're using activesupport (part of rails), you can take advantage of 2 extra methods on Hash
:
Hash#slice
takes the desired keys as separate arguments (not an array of keys) and returns a new hash with just the keys you asked for.
Hash#except
takes the same arguments as slice
, but returns a new hash with keys that were not in the arguments.
First load activesupport:
require 'active_support/core_ext'
Merge only entries from j
whose keys are already in h
(i.e. modify, but don't add any or remove entries in h
):
h.merge(j.slice(*h.keys))
Example:
ignore_new = ->(h, j) { h.merge(j.slice(* h.keys)) }
ignore_new.({a: 1, b: 2, c: 3}, {b: 10, c: 11, d: 12})
# => {:a=>1, :b=>10, :c=>11}
Get the leftovers from j
that weren't in h
:
j.except(*h.keys)
Bonus:
If you want true intersection, meaning you want a result that only has keys that are in common between the 2 hashes, do this:
h.merge(j).slice(* ( h.keys & j.keys ) )
Example:
intersect = ->(h, j) { h.merge(j).slice(* (h.keys & j.keys) ) }
intersect.({a: 1, b: 2, c: 3}, {b: 10, c: 11, d: 12})
# => {:b=>10, :c=>11}
and leftovers from h
that weren't in j
:
h.except(*j.keys)
You may also want to use activesupport's HashWithIndifferentAccess
if you want string & symbol key-access to be considered equivalent.
Note that none of the above examples change the original hashes; new hashes are returned instead.