How do I use the fetch method for nested hash?

后端 未结 7 1474
后悔当初
后悔当初 2021-02-19 14:45

I have the following hash:

hash = {\'name\' => { \'Mike\' => { \'age\' => 10, \'gender\' => \'m\' } } }

I can access the age by:

7条回答
  •  时光取名叫无心
    2021-02-19 15:21

    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).

提交回复
热议问题