Reputation: 4282
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?
Edit : I had this problem in multiple settings (python, ruby, markdown). 2 years later I finally understood : I always type space while still holding AltGr from a previous or following character that needs it. That makes an insecable space, see How to disable non-breaking space with altgr+space for a solution).
Upvotes: 3
Views: 10378
Reputation: 34774
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.
Upvotes: 5