From: Peter Ertl Date: 2006-03-24T22:27:58+09:00 Subject: Re: iterator class not working Hello Robert, thanks for your feedback. Yield'ing and using Array.[] seems obvious but I want class 'Iterator' to work for any 'Enumerable', not only 'Array'. The intention for using 'binding' is that I expect / hope it will keep track of the enumeration state inside 'Enumeration.each'. However, I don't know if that's possible in ruby at all. > --- Urspr�ngliche Nachricht --- > Von: "Robert Dober" > An: ruby-talk@ruby-lang.org (ruby-talk ML) > Betreff: Re: iterator class not working > Datum: Fri, 24 Mar 2006 22:17:32 +0900 > > On 3/24/06, Peter Ertl wrote: > > > > Hi, > > > > in order to understand ruby better (and for fun reasons of course) I try > > to > > write an iterator class. this way I want to understand 'binding' and > > 'callcc' better. > > > > however, it does not work! :-( > > > > any help will be greatly appreciated!!! > > > > --------------------------------------------- > > > > class Iterator > > > > def initialize(enum) > > @context = binding > > end > > > > def next > > enum = eval("enum", @context) > > @context, item = callcc do |cont| > > enum.each do |item| > > cont.call binding, item > > > ^ > | > ------------------------+ > you are missing "state" here, each time you call next, you start to > iterate > over your "enum" and > jump out of the iterator at the first iteration, that is giving you "mary" > all the time. > > > end > > end > > item > > end > > > > end > > > > names = %w{mary gordy john jane elwood} > > > > it = Iterator.new(names) > > > > 3.times do > > puts it.next > > end > > > > > mary > > > mary > > > mary > > > > Best regards > > Peter > > > > > Well I see why it does not work, but I fail to see your design behind the > thing > it could be done like this > class Iterator > def initialize(*args); @items=args;@i=-1;end > > def next > @i+=1; return @items[@i] unless block_given?; yield @items[@i]; end > end > but I do not really know what that would be good for. > > Cheers > Robert > > -- > Deux choses sont infinies : l'univers et la b�tise humaine ; en ce qui > concerne l'univers, je n'en ai pas acquis la certitude absolue. > > - Albert Einstein >