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

ruby, ruby-on-rails

Solution

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

Problem

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!

Original source

Related problems