From: William Morgan Date: 2005-03-16T00:32:48+09:00 Subject: Re: Is iterating in lock-step possible? Excerpts from Roshan James's mail of 15 Mar 2005 (EST): > At this point I need to ask you a question - > How do internal iterators work? How do they manage state? I havent seen > a description of this anywhere. > I know about creating objects for iteration. How do the internal > itertors differ from these? The iteration state is all in the iterator method. For example, look at how the Fibonacci series is written: def fib a = 1 b = 0 yield 0 while true x = a + b yield x a = b b = x end end fib { |n| puts n; break if n > 100 } All the state (a, b, and x) is in the iterator method. So the difference between external and internal iterators is: rather than repeatedly calling an "step" method on an "iterator object" and doing something with the result, you call an "iterator method" once, and pass it a lexical closure (in Ruby, a Proc object), and *it* then calls the Proc on each element. Internal iterators are not a Ruby-specific construct, nor are they explicitly built-in to Ruby, except in the sense that the syntactic sugar makes them very easy to do, and the API uses them all over. Think of them as a different "style" of iteration. Hope that answers your question. -- William