Skip to content

Instantly share code, notes, and snippets.

@tomquas
Forked from georgkreimer/hash_intersection.rb
Created October 29, 2013 14:37
Show Gist options
  • Save tomquas/7215858 to your computer and use it in GitHub Desktop.
Save tomquas/7215858 to your computer and use it in GitHub Desktop.
first = {"a" => 4, "b" => 1, "c" => 3, "g" => 201, "h" => 501}
second = {"d" => 19, "e" => 18, "c" => 17, "g" => 201, "h" => 501}
keys_intersection = first.keys & second.keys
merged = first.dup.update(second)
intersection = {}
keys_intersection.each do |k|
intersection[k]=merged[k] unless first[k] != second[k]
end
# same thing as freedom patch
class Hash
def intersection(another_hash)
keys_intersection = self.keys & another_hash.keys
merged = self.dup.update(another_hash)
intersection = {}
keys_intersection.each {|k| intersection[k] = merged [k] unless self[k] != another_hash[k]}
intersection
end
end
{"a" => 4, "b" => 1, "c" => 3, "g" => 201, "h" => 501}.intersection({"d" => 19, "e" => 18, "c" => 17, "g" => 201, "h" => 501})
=> {"g"=>201, "h"=>501}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment