Skip to content

Instantly share code, notes, and snippets.

@mferrier
Created July 19, 2013 15:33
Show Gist options
  • Save mferrier/6040051 to your computer and use it in GitHub Desktop.
Save mferrier/6040051 to your computer and use it in GitHub Desktop.
hash value by dotted string key
# 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