How do I use the fetch method for nested hash?

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

    From Ruby 2.3.0 onward, you can use Hash#dig:

    hash.dig('name', 'Mike', 'age')
    

    It also comes with the added bonus that if some of the values along the way turned up to be nil, you will get nil instead of exception.

    You can use the ruby_dig gem until you migrate.

    0 讨论(0)
提交回复
热议问题