I have the following hash:
hash = {\'name\' => { \'Mike\' => { \'age\' => 10, \'gender\' => \'m\' } } }
I can access the age by:
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)