How do I use the fetch method for nested hash?

后端 未结 7 1433
后悔当初
后悔当初 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

    As of Ruby 2.3.0:

    You can also use &. called the "safe navigation operator" as: hash&.[]('name')&.[]('Mike')&.[]('age'). This one is perfectly safe.

    Using dig is not safe as hash.dig(:name, :Mike, :age) will fail if hash is nil.

    However you may combine the two as: hash&.dig(:name, :Mike, :age).

    So either of the following is safe to use:

    hash&.[]('name')&.[]('Mike')&.[]('age')

    hash&.dig(:name, :Mike, :age)

提交回复
热议问题