Jasper Kennis
Jasper Kennis

Reputation: 3062

Check for nil warns about unexpected nil

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?

Upvotes: 1

Views: 447

Answers (4)

sawa
sawa

Reputation: 168071

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

Upvotes: 0

jonepatr
jonepatr

Reputation: 7809

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

Upvotes: 2

Michael Kohl
Michael Kohl

Reputation: 66837

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

http://andand.rubyforge.org/

Upvotes: 2

orlp
orlp

Reputation: 117641

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?

Upvotes: 4

Related Questions