Skip to content

Instantly share code, notes, and snippets.

@h3h
Created March 10, 2011 00:09
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 h3h/863294 to your computer and use it in GitHub Desktop.
Save h3h/863294 to your computer and use it in GitHub Desktop.
Hash#&
class Hash
# Intersection on hash keys (and values) that actually returns a Hash.
# The RHS can be an Array or a Hash.
#
# == Examples:
# >> hsh = {:banana => "elephant", :bar => "foo", :baz => "wuux"}
# >> hsh & [:bar]
# => {:bar=>"foo"}
#
# >> hsh & {:bar => "foo", :baz => "wuux"}
# => {:bar=>"foo", :baz=>"wuux"}
#
# >> hsh & {:bar => "foo", :baz => 1}
# => {:bar=>"foo"}
def &(array_or_hash)
array_or_hash.inject({}) do |a, (k, v)|
(!v || self[k] == v) ? a.merge(k => self[k]) : a
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment