Skip to content

Instantly share code, notes, and snippets.

@nyx
Created February 15, 2012 15:14
Show Gist options
  • Save nyx/1836553 to your computer and use it in GitHub Desktop.
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
# 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