From: Rick DeNatale Date: 2007-06-06T06:02:08+09:00 Subject: Re: Reverse-range alternatives? First let me take the liberty of reversing the top posting: On 6/5/07, Kenneth McDonald wrote: > Daniel DeLorme wrote: > > > > I can't resist this one... > > > > class Range > > def reverse > > r = dup > > def r.each(&block) > > last.downto(first, &block) > > end > > r > > end > > end > > I'd thought of that, but it's simply too risky. Changing the behavior of > something as fundamental as Range could really screw up if another > required module counted on that behavior. > > Generally, I'll reopen a class to add methods to it, but not to change > its behavior. Actually if you look carefully that's what his code does. He added a method to range which returns a new instance of range with a singleton method which overrides each. Normal instances of range won't be affected. It's a nice usage of the nested method definitions we were discussing recently. Bravo Daniel. Of course the reversed range should probably also invariants like: (1..3).reverse.last == (1..3).reverse.to_a.last And methods like to_s and step should also do the right thing too. If you want to go that far it's probably better to have a ReverseRange class and have the Range#reverse return an instance of that. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/