view raw
Jylo Jylo - 9 months ago 30
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

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.each { |i|
puts i

But this one does not:

@violation_array = []
(0..2).to_a.each{ |i|
@violation_array.each { |violation|
puts violation

and produces this error:

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

The value of
just before the

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

Any idea on why this array lacks the


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.