How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?
问题 I\'m looking for a good way to avoid checking for nil at each level in deeply nested hashes. For example: name = params[:company][:owner][:name] if params[:company] && params[:company][:owner] && params[:company][:owner][:name] This requires three checks, and makes for very ugly code. Any way to get around this? 回答1: Ruby 2.3.0 introduced a new method called dig on both Hash and Array that solves this problem entirely. name = params.dig(:company, :owner, :name) It returns nil if the key is