Created
February 4, 2014 15:38
-
-
Save nyx/8806014 to your computer and use it in GitHub Desktop.
easily dig values out of deeply nested hash with useful index error reporting
This file contains hidden or 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
class Hash | |
def dig(*keys) | |
#puts "dig: #{keys.inspect} #{self.inspect}" | |
if keys.empty? | |
return self | |
else | |
begin | |
v = self.fetch(keys.first) | |
return v if(keys.size.eql?(1)) | |
v.dig(*keys.drop(1)) | |
rescue IndexError => e | |
message = "IndexError: no such key: #{keys.first.inspect} in #{self.inspect}" | |
Airbrake.notify(e, {error_message: message}) | |
return nil | |
end | |
end | |
end | |
end | |
## example usage: | |
## a = {:a => {:b => {:c => 3}}} | |
## puts a.dig(:a,:b,:c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment