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

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.

Leave a Comment