-
-
Save szalansky/3839846 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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