Created
February 15, 2012 15:14
-
-
Save nyx/1836553 to your computer and use it in GitHub Desktop.
Patch Ruby's Hash class to simplify access and improve error messages. dig is useful for rummaging through deeply nested hashes
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
# patch Ruby's Hash class to simplify access and improve error messages | |
# useful for digging through deeply nested hashes | |
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