问题
I have the following check for nil:
client = !deal['deal']['party']['party'].nil? ? deal['deal']['party']['party']['company_id'] : ""
but still I get:
You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]
How can I prevent this?
回答1:
I don't know Ruby, but I think it goes wrong before the .nil:
deal['deal']['party']['party']
^ ^ ^
The arrows indicate possible nil indexes. For example, what if ["deal"] is nil or the first ["party"] is nil?
回答2:
You might want to have a look at the andand game:
http://andand.rubyforge.org/
回答3:
By checking !deal.nil? and !deal['deal'].nil? and !deal['deal']['party'].nil? and !deal['deal']['party']['party'].nil?
回答4:
At each step, you can use an appropriate method built in NilClass to escape from nil, if it were array, string, or numeric. Just add to_hash to the inventory of this list and use it.
class NilClass; def to_hash; {} end end
client = deal['deal'].to_hash['party'].to_hash['party'].to_hash['company_id'].to_s
You can also do:
client = deal.fetch('deal', {}).fecth('party', {}).fetch('party', {}).fetch('company_id', '')
来源:https://stackoverflow.com/questions/4656742/check-for-nil-warns-about-unexpected-nil