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.
From the fine manual:
Emphasis mine. So all of the iterative behavior of Enumerable is based on the class’s
eachmethod; the ordering parts of the Enumerable interface (min,max,sort) use<=>but that’s not important here.The supplied
eachmethod is the only defined way that Enumerable has to interact with the class that mixes it in. Enumerable supplies ato_amethod so it must useeachto implement it.As an aside, Enumerable does its best not to call
to_aunless it has to, it tries to keep everything as an Enumerable to avoid having to exhaust the enumeration to build an Array that could be expensive in both time and space. The answer that Yossi pointed out is more about when Enumerable callsto_arather than how (but that answer is interesting reading nonetheless ;).