1
votes

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?

4
Don’t answer questions that have already been answered elsewhere. Yeah, you might earn a couple of points of reputation, but, because you are duplicating content, you are actually making the internet worse. (c) JeffNakilon
That wasn't my question, I wasn't looking for something "nicer" I just ran into trouble finding out why my check on nil kept returning an unexpected nil error.Jasper Kennis

4 Answers

4
votes

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
votes

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

http://andand.rubyforge.org/

2
votes

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

0
votes

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