Ruby:尝试在散列数组上获取枚举数时,未定义 nil:NilClass 的方法“[]”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41514057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:52:14  来源:igfitidea点击:

Ruby: undefined method `[]' for nil:NilClass when trying to get Enumerator on an Array of Hashes

arraysrubyhashenumerator

提问by Joe Toug

I am trying to loop on an Array of Hashes. When I reach the point where I fetch the Enumerator to start looping, I get the following error:

我正在尝试循环哈希数组。当我到达获取 Enumerator 以开始循环的点时,出现以下错误:

undefined method `[]' for nil:NilClass

My code looks like the following:

我的代码如下所示:

def extraireAttributs (attributsParam)
  classeTrouvee = false
  scanTrouve = false
  ownerOSTrouve = false
  ownerAppTrouve = false
  resultat = Hash.new(0)
  attributs = Array(attributsParam)

  attributs.each do |attribut| #CRASHES HERE!!!
    typeAttribut = attribut['objectTypeAttribute']
    [...]

I checked in debug mode to make sure the attributsParamsargument and the attributsvariable are not nil or empty. Both (because they are the same!) contain 59 Hashes objects, but I still cannot get an Enumerator on the Array.

我在调试模式下检查以确保attributsParams参数和attributs变量不为零或为空。两者(因为它们是相同的!)都包含 59 个 Hashes 对象,但我仍然无法在数组上获得枚举器。

Why do I keep on getting this error?

为什么我不断收到此错误?

Thanks!

谢谢!

回答by Schwern

undefined method `[]' for nil:NilClasssays you tried to do something[index]but somethingis nil. Ruby won't let you use nilas an array (ie. call the []method on it).

undefined method `[]' for nil:NilClass说你试图做something[index]但是somethingnil。Ruby 不会让您nil用作数组(即调用[]它的方法)。

The problem is not on the attributs.eachline but on the line following which calls the []method on attribut.

问题不在attributs.each行上,而是在调用[]on 方法的行上attribut

typeAttribut = attribut['objectTypeAttribute']

This indicates something in attributsis nil. This could happen if attributsParamis a list that contains nil like so.

这表明里面的东西attributs为零。如果attributsParam是一个包含 nil 的列表,则可能会发生这种情况。

attributsParam = [nil];
attributs = Array(attributsParam);

# [nil]
puts attributs.inspect

Simplest way to debug it is to add puts attributs.inspectjust before the loop.

调试它的最简单方法是puts attributs.inspect在循环之前添加。

Also consider if you really need the attributs = Array(attributsParam)line or if it's already something Enumerable.

还要考虑您是否真的需要该attributs = Array(attributsParam)行,或者它是否已经是Enumerable