How to idiomatically check if a Hash is not nil and so get value of a key in one line in Ruby on Rails?

Viewed 1555

First I want to check for nil. If it is not nil, then get value of key

1 Answers

A typical way would be val = hash && hash[key] or val = hash[key] if hash.

You can also use the safe navigation operator, like val = hash&.dig(key) (see Hash#dig) or val = hash&.[](key) .. I wouldn't really recommend that last one since it's not very readable

All of those examples will set val to nil if the hash is nil. If the key must exist and you want to raise an error if it doesn't, you can use val = hash&.fetch(key) (see Hash#fetch)

Related