Skip to content

Instantly share code, notes, and snippets.

@reactormonk
Forked from madsheep/hash.rb
Created December 14, 2011 10:54
Show Gist options
  • Save reactormonk/1476114 to your computer and use it in GitHub Desktop.
Save reactormonk/1476114 to your computer and use it in GitHub Desktop.
Hardcore deep hash
class Hash
define_method '[]_with_try_on', do |*args|
if args.size == 1 and respond_to?(args.first)
send(:'[]_with_try_on', args.first)
else
args.inject(self.dup){|memo, e| memo.dup.delete(e) if memo.is_a?(Hash) }
end
end
alias_method_chain :[], :try_on
end
#ruby-1.9.2-head :164 > {}[:a, :b]
# => nil
#ruby-1.9.2-head :165 > {:a => {:b => "c"}}[:a, :b]
# => "c"
#ruby-1.9.2-head :166 > {:a => {:b => "c"}}[:a, :b, :c]
# => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment