Skip to content

Instantly share code, notes, and snippets.

@the-architect
Last active August 29, 2015 14:02
Show Gist options
  • Save the-architect/4b1bd6c696c2f3540447 to your computer and use it in GitHub Desktop.
Save the-architect/4b1bd6c696c2f3540447 to your computer and use it in GitHub Desktop.
Hash#fetch with multiple keys => Hash.path
module CoreExt
module PathExtension
# this method recursively calls fetch with every key you provide
# the last key argument is used as the default value
def path(*keys)
key = keys.shift
case keys.length
when 0
key
when 1
fetch(key, keys.last)
else
# fetch next key, default to hash
val = self.fetch(key, {})
if val.respond_to?(:path)
val.path(*keys)
else
# we got a non-hash value back, so we return the value directly
val
end
end
end
end
end
class Hash
include CoreExt::PathExtension
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment