开发者

Check for nil warns about unexpected nil

开发者 https://www.devze.com 2023-02-03 09:30 出处:网络
I have the following check for nil: client = !deal[\'deal\'][\'party\'][\'party\'].nil? ? deal[\'deal\'][\'party\'][\'party\'][\'company_id\'] : \"\"

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 d开发者_开发百科idn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]

How can I prevent this?


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?


You might want to have a look at the andand game:

http://andand.rubyforge.org/


By checking !deal.nil? and !deal['deal'].nil? and !deal['deal']['party'].nil? and !deal['deal']['party']['party'].nil?


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', '')
0

精彩评论

暂无评论...
验证码 换一张
取 消