解決常見的
NoMethodError: undefined method '[]' for nil:NilClass
Ruby 2.3.0 之後才能用
params = { user: { address: { street: '123 Fake Street', town: 'Faketon', postcode: '12345' } } }
street = params[:user] && params[:user][:address] && params[:user][:address][:street]
street = params.dig(:user, :address, :street)
street = user&.address&.street
Ruby 2.3 以前
安裝 gem 'ruby_dig'
另一種常見的情況
h = {}
h[:a][:b][:c] = "abc" # NoMethodError: undefined method '[]' for nil:NilClass
h = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
h[:a][:b][:d][:c] = "abc" # { :a => { :b => { :c => "abc" } } }