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

1

18

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:

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.

Why do I keep on getting this error?

Thanks!

Veterinary answered 6/1, 2017 at 20:44 Comment(3)
Are you sure it's there and not the following line?Nuts
Are you sure it's not on later code? It's hard to know without line numbers, could you provide line numbers?Nuts
How does attributsParam look like? If there are too many hashes, just show 3 of them!Conto
N
25

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

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

typeAttribut = attribut['objectTypeAttribute']

This indicates something in attributs is nil. This could happen if attributsParam is a list that contains nil like so.

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

# [nil]
puts attributs.inspect

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

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

Nuts answered 6/1, 2017 at 20:56 Comment(1)
You are right. The inner structure of the hashes which are inside the outer array have changed. Therefore the exception happened inside the loop. Thanks a lot!Veterinary

© 2022 - 2024 — McMap. All rights reserved.