Jylo Jylo - 4 months ago 8
Ruby Question

Undefined method `each ' for an array

I'm trying to iterate over an array containing various instances of a class for a test case. An array should have an

each
function according to the RubyDoc:


Like all classes that include the Enumerable module, Array has an each method, which defines what elements should be iterated over and how.


The following code works:

@array = []
(0..20).to_a.each{ |i|
@array.push(i)
}
@array.each { |i|
puts i
}


But this one does not:

@violation_array = []
(0..2).to_a.each{ |i|
@violation_array.push(Violation.new("violation#{i}"))
}
@violation_array.each { |violation|
puts violation
}


and produces this error:

NoMethodError: undefined method `each ' for #<Array:0x007f3aa232ece8>


The value of
@violation_array.inspect
just before the
each
is:

[#<Violation:0x007f71e4965e30 @key="violation0">, #<Violation:0x007f71e4965bb0 @key="violation1">, #<Violation:0x007f71e49657f0 @key="violation2">]


Any idea on why this array lacks the
each
function?

Answer

I think the error message may be illuminating. There's a space in the method name so the method that doesn't exist is "each ". Somehow I think you've got some spurious whitespace appearing in your code. There definitely is an "each" method on arrays but not an "each " method.