Jan Jan - 15 days ago 7
Ruby Question

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!


This error is raised because one of the hash values in the chain of omniauth['extra']['raw_info']['location']['name'].nil? returns nil and it is not the last call ['name'].

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

You can catch this error simply:

res = omniauth['extra']['raw_info']['location']['name'].nil? rescue true

unless res
  #your code here

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