简体   繁体   English

如何为nil捕获“未定义的方法`[]”:NilClass“错误?

[英]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? 我通过omniauth从facebook获得一个嵌套数组,并想检查它是否为空?/ 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?" 我用“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? 引发此错误是因为omniauth['extra']['raw_info']['location']['name'].nil?链中的一个哈希值omniauth['extra']['raw_info']['location']['name'].nil? returns nil and it is not the last call ['name']. 返回nil并且它不是最后一次调用['name']。

If for example omniauth['extra']['raw_info'] returns nil, you're actually trying to call nil['location'] which raises an error in ruby. 例如,如果omniauth['extra']['raw_info']返回nil,那么你实际上是在尝试调用nil['location'] ,这会在ruby中引发错误。

You can catch this error simply: 您可以简单地捕获此错误:

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

unless res
  #your code here
end

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. 请注意,如果['name']哈希值为nil或链中的任何其他哈希值返回nil,则上面的代码块将填充变量res为true。

Ideally you should check each nested level to see if it is nil , however, this will also work. 理想情况下,您应该检查每个嵌套级别以查看它是否为nil ,但是,这也可以。

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

You can also rescue the NoMethodError specifically. 您还可以专门解救NoMethodError

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 . 派对有点晚了,但是,正如在这个答案中指出的那样,Ruby 2.3.0 引入了一个名为dig 的新方法 ,如果其中一个链式密钥nil则返回nil Your omniauth auth hash could then be presented as: 您的omniauth auth哈希可以表示为:

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


omniauth.dig('extra', 
             'raw_info',
             'location',
             'name',
             'foo',
             'bar',
             'baz') #<= nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM