Last active
August 29, 2015 14:02
-
-
Save the-architect/4b1bd6c696c2f3540447 to your computer and use it in GitHub Desktop.
Hash#fetch with multiple keys => Hash.path
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
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