I can write a short example that verifies that to_a
of Enumerable
calls each
internally. Here it is:
class MyFooClass
include Enumerable
def initialize
@members = [1, 2, 3]
end
def each
puts "each is now called"
@members.each{ |m| yield(m) }
end
end
a = MyFooClass.new
puts "let us convert to array"
g = a.to_a
The output is:
let us convert to array
each is now called
Note that each
is not member of Enumerable
, but to_a
is. Also, if I remove the definition of each
from my class, then code crashes with the following message:
in `to_a': undefined method `each' for #<MyFooClass:0x997c1ac @members=[1, 2, 3]> (NoMethodError)
I am wondering whether there is Ruby official documentation about this, that would document the fact that to_a
(which is member of Enumerable
) goes through each
method in your class. Please, do not direct me to source code of to_a
. I do not consider this an answer.