Created
July 19, 2013 15:33
-
-
Save mferrier/6040051 to your computer and use it in GitHub Desktop.
hash value by dotted string key
This file contains 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
# hash = {'a' => {'b' => {'c' => 1}}} | |
# path = "a.b.c" | |
# hash_value_by_dotted_notation(hash, path) | |
# => 1 | |
# invalid path returns nil | |
def hash_value_by_dotted_notation(hash, dotted_path) | |
val = hash | |
dotted_path.to_s.split(".").each do |k| | |
val = (val.is_a?(Hash) && val.has_key?(k)) ? val[k] : nil | |
end | |
val == hash ? nil : val | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment