Skip to content

Instantly share code, notes, and snippets.

@szalansky
Forked from teamon/hash.rb
Created October 5, 2012 13:36
Show Gist options
  • Save szalansky/3839846 to your computer and use it in GitHub Desktop.
Save szalansky/3839846 to your computer and use it in GitHub Desktop.
# Instead of:
# hash[:a].try(:[], :b).try(:[], :c).try(:[], :d)
# you can write
# hash[:a, :b, :c, :d]
class Hash
# h = {:a => {:b => {:c => 1}}}
# p h[:a] # => {:b => {:c => 1}}
# p h[:a, :b] # => {:c => 1}
# p h[:a, :b, :c] # => 1
# p h[:a, :b, :c, :d] # => nil
# p h[:x, :y, :z] # => nil
alias_method :_orig_get, :[]
def [](*args)
args.inject(self){|h,k| h.try(:_orig_get, k) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment