如何为 nil:NilClass 捕获“未定义的方法‘[]’"错误? [英] How to catch an "undefined method `[]' for nil:NilClass" error?
问题描述
我通过 omniauth 从 facebook 获取了一个嵌套数组,想检查它是否为空?/nil?/exists?依赖线看起来像:
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.
但总是抛出这个错误:
undefined method `[]' for nil:NilClass
我检查数组有错吗?
我用has_key"nil"试过了?空的?"存在吗?"空白?"
I tried it with "has_key" "nil?" "empty?" "exists?" "blank?"
但这些都没有用!
请帮助我,非常感谢!
推荐答案
聚会有点晚,但是,正如 this答案,Ruby 2.3.0 引入了一个新方法称为dig
,如果链式键之一是nil
,它将返回nil
.您的 omniauth auth 哈希可以表示为:
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
这篇关于如何为 nil:NilClass 捕获“未定义的方法‘[]’"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!