From: Florian Gross Date: 2004-09-06T04:50:12+09:00 Subject: Re: Style Question 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? > 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) > 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 > end > Kind regards > robert More regards, Florian Gross