I have the following hash:
hash = {'name' => { 'Mike' => { 'age' => 10, 'gender' => 'm' } } }
I can access the age by:
hash['name']['Mike']['age']
What if I used Hash#fetch
method? How can I retrieve a key from a nested hash?
As Sergio mentioned, the way to do it (without creating something for myself) would be by a chain of fetch
methods:
hash.fetch('name').fetch('Mike').fetch('age')
EDIT: there is a built-in way now, see this answer.
There is no built-in method that I know of. I have this in my current project
class Hash
def fetch_path(*parts)
parts.reduce(self) do |memo, key|
memo[key.to_s] if memo
end
end
end
# usage
hash.fetch_path('name', 'Mike', 'age')
You can easily modify it to use #fetch
instead of #[]
(if you so wish).