Check for nil warns about unexpected nil

ぃ、小莉子 提交于 2019-12-13 18:33:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!