Skip to content

Instantly share code, notes, and snippets.

@bjeanes
Created July 7, 2017 06:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjeanes/fce0c04b05fbfd00514d8ad434dbece5 to your computer and use it in GitHub Desktop.
Save bjeanes/fce0c04b05fbfd00514d8ad434dbece5 to your computer and use it in GitHub Desktop.
class Hash
# Returns a nested intersection of two Hashes.
#
# This draws a parallel to &/intersect on Array and Set.
#
# FIXME: However, those methods are not recursive, so it may make more sense
# to give this another name.
#
# Examples:
#
# {a: 1} & {a: 2} #=> {}
# {a: 1} & {b: 2} #=> {}
# {a: 1} & {a: 1, b: 2} #=> {a: 1}
# {a: 1, b: {c: 3, d: 10}} & {a: 1, b: {c: 3, d: 9}} #=> {a: 1, b: {c: 3}}
# {a: 1, b: {c: 3, d: 10}} & {a: 2, b: {c: 3, d: 9}} #=> {b: {c: 3}}
#
def &(other)
return {} unless other.is_a?(Hash)
shared_keys = keys & other.keys
shared_keys.each_with_object({}) do |key, intersection|
a, b = self[key], other[key]
if a == b
intersection[key] = a
elsif a.is_a?(Hash) && b.is_a?(Hash)
intersection[key] = a & b
end
end
end
alias intersection &
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment