How to avoid NoMethodError for nil elements when accessing nested hashes? [duplicate]

Ruby 2.3.0 introduced a new method called dig on both Hash and Array that solves this problem entirely.

It returns nil if an element is missing at any level of nesting.

h1 = {}
h2 = { a: {} }
h3 = { a: { b: 100 } }

h1.dig(:a, :b) # => nil
h2.dig(:a, :b) # => nil
h3.dig(:a, :b) # => 100

Your use case would look like this:

@param_info.dig('drug', 'name')

Leave a Comment