Created
March 2, 2012 01:29
-
-
Save re5et/1954628 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
class Hash | |
def dig(*path) | |
path.inject(self) do |location, key| | |
location.is_a?(Hash) ? location[key] : nil | |
end | |
end | |
end |
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
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
http://stackoverflow.com/questions/1820451/ruby-style-how-to-check-whether-a-nested-hash-element-exists