-
-
Save remino/34d86853beb8688bd81f to your computer and use it in GitHub Desktop.
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
class Hash | |
def dig(*path) | |
path.inject(self) do |location, key| | |
location.is_a?(Hash) ? location[key] : nil | |
end | |
end | |
end |
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
1.9.3p0 :001 > h = {:foo => {:bar => {:baz => {:qux => true}}}} | |
=> {:foo=>{:bar=>{:baz=>{:qux=>true}}}} | |
1.9.3p0 :002 > h.dig(:foo, :bar, :baz, :qux) | |
=> true | |
1.9.3p0 :003 > h.dig(:foo, :bar, :baz, :qux, :barf) | |
=> nil | |
1.9.3p0 :004 > h.dig(:foo, :bar) | |
=> {:baz=>{:qux=>true}} | |
1.9.3p0 :005 > h.dig(:foo, :bar, :flapjacks) | |
=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment