Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.