Skip to content

Instantly share code, notes, and snippets.

@h3h h3h/hash.rb
Created Mar 10, 2011

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