How do I use the fetch method for nested hash?

后端 未结 7 1422
后悔当初
后悔当初 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:19

    If you don't want to monkey patch the standard Ruby class Hash use .fetch(x, {}) variant. So for the example above will look like that:

    hash.fetch('name', {}).fetch('Mike', {}).fetch('age')
    

提交回复
热议问题