Created
July 7, 2017 06:18
-
-
Save bjeanes/fce0c04b05fbfd00514d8ad434dbece5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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