繁体   English   中英

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

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

我通过omniauth从facebook获得一个嵌套数组,并想检查它是否为空?/ nil?/ exists? 依赖行看起来像:

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

这应该检查数组的这一部分是空的还是存在的。

但总是抛出这个错误:

undefined method `[]' for nil:NilClass

我检查数组错了吗?

我用“has_key”“nil尝试了吗?” “空的?” “存在?” “空白?”

但这些都没有!

请帮帮我,非常感谢!

引发此错误是因为omniauth['extra']['raw_info']['location']['name'].nil?链中的一个哈希值omniauth['extra']['raw_info']['location']['name'].nil? 返回nil并且它不是最后一次调用['name']。

例如,如果omniauth['extra']['raw_info']返回nil,那么你实际上是在尝试调用nil['location'] ,这会在ruby中引发错误。

您可以简单地捕获此错误:

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

unless res
  #your code here
end

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

理想情况下,您应该检查每个嵌套级别以查看它是否为nil ,但是,这也可以。

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

您还可以专门解救NoMethodError

派对有点晚了,但是,正如在这个答案中指出的那样,Ruby 2.3.0 引入了一个名为dig 的新方法 ,如果其中一个链式密钥nil则返回nil 您的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