Skip to content

Instantly share code, notes, and snippets.

@GBH
Created November 6, 2012 21:35
Show Gist options
  • Save GBH/4027748 to your computer and use it in GitHub Desktop.
Save GBH/4027748 to your computer and use it in GitHub Desktop.
Hash#dig
class Hash
# Accessing deep hash values. For example, given this hash:
# h = {:a => {:b => :c}}
# h.dig(:a, :b)
# => :c
# h.dig(:x, :y, :z)
# => nil
def dig(*path)
first, tail = path[0], path[1..-1]
node = self[first]
if tail.size > 0
node.is_a?(Hash) ? node.dig(*tail) : nil
else
node
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment