Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an "undefined method `[]' for nil:NilClass" error?

I get an nested array from facebook via omniauth and wanna check if it's empty?/nil?/exists? the depending line looks like:

 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

Do I check arrays wrong?

I tried it with "has_key" "nil?" "empty?" "exists?" "blank?"

But no one of these works!

Please help me, many thanks in advance!

like image 484
Jan Avatar asked Jul 16 '12 09:07

Jan


1 Answers

A bit late to the party, but, as pointed in this answer, Ruby 2.3.0 introduced a new method called dig, which would return nil if one of the chained keys is nil. Your omniauth auth hash could then be presented as:

omniauth = { 
            ...                 
            "extra"=>{ "raw_info"=>
                        { "location"=>"New York",
                          "gravatar_id"=>"123456789"}}
             ...
           }


omniauth.dig('extra', 
             'raw_info',
             'location',
             'name',
             'foo',
             'bar',
             'baz') #<= nil
like image 127
dimitry_n Avatar answered Oct 07 '22 12:10

dimitry_n