Skip to content

Instantly share code, notes, and snippets.

@remino
Forked from re5et/dig.rb
Last active August 29, 2015 14:23
Show Gist options
  • Save remino/34d86853beb8688bd81f to your computer and use it in GitHub Desktop.
Save remino/34d86853beb8688bd81f to your computer and use it in GitHub Desktop.
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