Skip to content

Instantly share code, notes, and snippets.

@teamon
Created October 26, 2011 07:53
Show Gist options
  • Save teamon/1315728 to your computer and use it in GitHub Desktop.
Save teamon/1315728 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