Skip to content

Instantly share code, notes, and snippets.

@samstarling
Last active December 18, 2015 21:09
Show Gist options
  • Save samstarling/5845258 to your computer and use it in GitHub Desktop.
Save samstarling/5845258 to your computer and use it in GitHub Desktop.
Safe access of a nested hash from JSON in Ruby.
require 'json'
class Hash
def dig(*path)
path.inject(self) do |location, key|
location.respond_to?(:keys) ? location[key] : nil
end
end
end
x = JSON.parse('{ "foo": [1, 2, 3, 4] }')
puts x.dig("foo").inspect
puts x.dig("nonsense", "bar").inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment