How does Ruby's Enumerator object iterate externally over an internal iterator?

Posted by Salman Paracha on Stack Overflow See other posts from Stack Overflow or by Salman Paracha
Published on 2012-06-15T19:45:37Z Indexed on 2012/06/15 21:16 UTC
Read the original article Hit count: 221

Filed under:
|
|

As per Ruby's documentation, the Enumerator object uses the each method (to enumerate) if no target method is provided to the to_enum or enum_for methods. Now, let's take the following monkey patch and its enumerator, as an example

o = Object.new
def o.each
    yield 1
    yield 2
    yield 3
end
e = o.to_enum

loop do
  puts e.next
end

Given that the Enumerator object uses the each method to answer when next is called, how do calls to the each method look like, every time next is called? Does the Enumeartor class pre-load all the contents of o.each and creates a local copy for enumeration? Or is there some sort of Ruby magic that hangs the operations at each yield statement until next is called on the enumeartor?

If an internal copy is made, is it a deep copy? What about I/O objects that could be used for external enumeration?

I'm using Ruby 1.9.2.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about iterator