Skip to content

Instantly share code, notes, and snippets.

@remino
Created December 7, 2012 06:17
Show Gist options
  • Save remino/4231157 to your computer and use it in GitHub Desktop.
Save remino/4231157 to your computer and use it in GitHub Desktop.
Ruby Hash dig
# FROM http://stackoverflow.com/a/1820492/1186789
#
# Example:
#
# h = { a: { b: { c: 1, d: 2 } } }
# h.dig(:a, :b, :c) == 1
# h.dig(:a, :b) == { c: 1, d: 2 }
# h.dig(:x, :y, :z) == nil
class Hash
def dig(*path)
path.inject(self) do |location, key|
location.respond_to?(:keys) ? location[key] : nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment