Created
December 7, 2012 06:17
-
-
Save remino/4231157 to your computer and use it in GitHub Desktop.
Ruby 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
# 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