【问题标题】:Ruby: undefined method `[]' for nil:NilClass when trying to get Enumerator on an Array of HashesRuby:尝试获取哈希数组上的枚举器时,nil:NilClass 的未定义方法“[]”
【发布时间】:2017-01-06 20:44:35
【问题描述】:

我正在尝试循环一个哈希数组。当我到达获取枚举器开始循环的点时,我收到以下错误:

undefined method `[]' for nil:NilClass

我的代码如下所示:

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']
    [...]

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

为什么我不断收到这个错误?

谢谢!

【问题讨论】:

  • 你确定它在那里而不是下一行?
  • 你确定它不在后面的代码上吗?没有行号很难知道,能否提供行号?
  • attributsParam 长什么样子?如果哈希值太多,只显示其中的 3 个!

标签: arrays ruby hash enumerator


【解决方案1】:

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

问题不在于attributs.each 行,而在于在attribut 上调用[] 方法的下一行。

typeAttribut = attribut['objectTypeAttribute']

这表明attributs 中的某些内容为零。如果attributsParam 是一个包含 nil 的列表,就会发生这种情况。

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

# [nil]
puts attributs.inspect

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

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

【讨论】:

  • 你是对的。外部数组内的哈希的内部结构已更改。因此异常发生在循环内部。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2013-06-27
  • 2016-07-08
  • 1970-01-01
  • 2012-05-10
相关资源
最近更新 更多