From: Austin Ziegler Date: 2005-04-25T21:53:00+09:00 Subject: Re: How are Ruby iterators implemented? On 4/25/05, Roshan James wrote: > How are iterators implemented in Ruby? > > Sometime back I had asked a questuin about invoking iterators in > locksteps and I was told that iterators in ruby are implemented as > closures that are passed to the called method. If iterators are > passed as closures then, 1) Every consumer of the iterator should > undergo closure conversion in some way 2) How is "break" > implemented ? This similar to how it would be done in Scheme or > similar language that inherently supports closures. > > I was reading about CLU (the parent language for the iterator > concept), and they implemnted iterators on a single stack. I > believe that that would involve have caller and callee function > frames to live on the stack at the same time. The iteration would > be implemnetd as goto between these functions with a corresposding > shift in stock location to refernce locals. This implementation > has the inherent limitation of not being able to do multiple > itetarors in lock step. > > Another alternative is that the itetror is converted to an object > that maintains state - a classical generator. This is what C# and > Py do. > > How does Ruby do iterators ? What I'm getting ready to tell you is as far as I understand it; it may not be completely correct -- and the most authoritative way to see this is the source. That said, simple iterators like #each implement a loop through the container and yield the object in the iterator to the provided code block. #each suspends execution until the block (closure) finishes executing. That would generally indicate a change in stack frame. Ruby does have generators available, but they're overkill for ~95% of cases. -austin -- Austin Ziegler * halostatue@gmail.com * Alternate: austin@halostatue.ca