The Rails I18n library transforms a YAML file into a data structure that is accessible via a dotted path call using the t() function.
t(\'one.two.three.four\
This code not only allows dot notation to traverse a Hash but also square brackets to traverse Arrays with indices. It also avoids recursion for efficiency.
class Hash
def key_path(dotted_path)
result = self
dotted_path.split('.').each do |dot_part|
dot_part.split('[').each do |part|
if part.include?(']')
index = part.to_i
result = result[index] rescue nil
else
result = result[part] rescue nil
end
end
end
result
end
end
Example:
a = {"b" => {"c" => [0, [1, 42]]}}
a.key_path("b.c[-1][1]") # => 42