From: Robert Klemme Date: 2004-09-06T04:55:15+09:00 Subject: Re: Style Question "Florian Gross" schrieb im Newsbeitrag news:2q18quFqav8gU1@uni-berlin.de... > Robert Klemme wrote: > >>> Hello everybody, > > Moin! > >>> PS: How is for implemented? Can I maybe teach Number.downto to return an >>> object that >>> is used by for to iterate like an inverse range? >> Even more straightforward: you can implement a range that supports both >> directions yourself plus arbitrary stepping like this: > > I'd prefer using an enumerator around Range#step or Fixnum#step instead. > > Here are a few small comments and suggestion about your code. Maybe they > are useful. > >> class Rg >> include Enumerable >> >> def initialize(from, to, step = sign(to - from)) > > What about String Ranges? That was just meant as an example - implementing integer ranges. I probably should have pointed that out more clearly. >> raise ArgumentError, "Invalid step #{step}" if (to - from) * step <= 0 >> @from, @to, @step = from, to, step >> @to += @step - ((@to - @from) % @step) >> end >> >> def each >> x = @from >> until x == @to > > This is a problem -- there are Ranges that will never satisfy this > condition. (Float ranges come to mind) Yep, the int check is missing. >> yield x >> x += @step >> end >> self >> end >> >> def sign(x) >> case >> when x > 0 >> 1 >> when x == 0 >> 0 >> else >> -1 >> end >> end > > def sign(x); x <=> 0; end Very nice! Then we don't need sign(): def initialize(from, to, step = ((to - from) <=> 0)) >> end > >> Kind regards >> robert > > More regards, > Florian Gross EMR (even more regards) robert