Created
November 6, 2012 21:35
-
-
Save GBH/4027748 to your computer and use it in GitHub Desktop.
Hash#dig
This file contains hidden or 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
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