Skip to content

Instantly share code, notes, and snippets.

@madsheep
Created December 14, 2011 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save madsheep/1476030 to your computer and use it in GitHub Desktop.
Save madsheep/1476030 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 (args.is_a?(Symbol) or args.is_a?(String))
self.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