Last active
December 18, 2015 21:09
-
-
Save samstarling/5845258 to your computer and use it in GitHub Desktop.
Safe access of a nested hash from JSON in Ruby.
This file contains 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
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