Like Ruby 2.3.0:
You can also use &. , called the "safe navigation operator", like: hash&.[]('name')&.[]('Mike')&.[]('age') . It is absolutely safe.
Using dig unsafe because hash.dig(:name, :Mike, :age) will fail if hash is zero.
However, you can combine these two as: hash&.dig(:name, :Mike, :age) .
Thus, any of the following methods is safe to use:
hash&.[]('name')&.[]('Mike')&.[]('age')
hash&.dig(:name, :Mike, :age)
source share