In Rails, you can do hash.try(:[], :key)
which helps if hash
is potentially nil
.
Is there an equivalent version for using the new Ruby 2.3
Accepted answer will not account for when hash
is nil...
You can rewrite what you have using the safe nav operator before the .try
and that will work
hash&.try(:[], :key)
but you can also use:
http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig
A way you could do this on a hash is by doing...
hash&.dig(:key1, :key2 ...)
which will return nil if any key fetch isn't present.
{ key1: { key2: 'info' } }
would return 'info'
{ key1: { wrong_key: 'info' } }
would return nil