How to catch the undefined `[] 'method for nil: NilClass?

I get a nested array from facebook via omniauth and want to check if / nil? / Is empty? the dependent line is as follows:

unless omniauth['extra']['raw_info']['location']['name'].nil? 

This should check if this part of the array is empty or exists.

But always this error was thrown:

 undefined method `[]' for nil:NilClass 

Am I checking arrays incorrectly?

I tried it with "has_key" "nil?" "Empty?" "exists?" "Empty?"

But none of them work!

Please help me, thanks a lot in advance!

+9
source share
3 answers

A bit late for the party, but as pointed out in this answer , Ruby 2.3.0 introduced a new method called dig , which would return nil if one of the key chain is nil . Then your omniauth hash code could be represented as:

 omniauth = { ... "extra"=>{ "raw_info"=> { "location"=>"New York", "gravatar_id"=>"123456789"}} ... } omniauth.dig('extra', 'raw_info', 'location', 'name', 'foo', 'bar', 'baz') #<= nil 
+5
source

This error occurs because one of the hash values ​​in the omniauth['extra']['raw_info']['location']['name'].nil? chain. omniauth['extra']['raw_info']['location']['name'].nil? returns nil, and this is not the last call to ['name'].

If, for example, omniauth['extra']['raw_info'] returns nil, you are actually trying to call nil['location'] , which causes an error in ruby.

You can easily catch this error:

 res = omniauth['extra']['raw_info']['location']['name'].nil? rescue true unless res #your code here end 

Please note that the above code will fill the res variable with true if the hash value ['name'] is nil or any other hash value in the chain returns nil.

+13
source

Ideally, you should check each nested level to see if it is nil , however this will also work.

 unless (omniauth['extra']['raw_info']['location']['name'] rescue nil).nil? 

You can also save NoMethodError in particular.

+12
source

All Articles