Skip to content

Instantly share code, notes, and snippets.

@nyx
Created February 4, 2014 15:38
Show Gist options
  • Save nyx/8806014 to your computer and use it in GitHub Desktop.
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
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