If you use Rails, you can use try (and NilClass#try ):
value = map.try(:[], :extra).try(:[], :raw_info).try(:[], :birthday)
It looks a bit repetitive: it just does the same thing over and over, passing the result of one step to the next step. This code template means we have a hidden injection:
value = [:extra, :raw_info, :birthday].inject(map) { |h, k| h.try(:[], k) }
This approach generalizes well any path in map that you have in mind:
path = [ :some, :path, :of, :keys, :we, :care, :about ] value = path.inject(map) { |h, k| h.try(:[], k) }
Then you can look at value.nil? .
Of course, if you do not use Rails, you will need a replacement for try , but it is not difficult.
source share