Skip to content

Instantly share code, notes, and snippets.

@re5et
Created March 2, 2012 01:29
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save re5et/1954628 to your computer and use it in GitHub Desktop.
Save re5et/1954628 to your computer and use it in GitHub Desktop.
ruby hash dig
class Hash
def dig(*path)
path.inject(self) do |location, key|
location.is_a?(Hash) ? location[key] : nil
end
end
end
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