class Hash
def dig(dotted_path)
parts = dotted_path.split '.', 2
match = self[parts[0]]
if !parts[1] or match.nil?
return match
else
return match.dig(parts[1])
end
end
end
my_hash = {'a' => {'b' => 'a-b', 'c' => 'a-c', 'd' => {'e' => 'a-d-e'}}, 'f' => 'f'}
my_hash.dig('a.d.e') # outputs 'a-d-e' (by calling my_hash['a']['d']['e'])
Ref: http://stackoverflow.com/a/7139631
#####Another implementation with array
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