Kenneth McDonald
6/5/2007 5:07:00 AM
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.
Too bad, though, that the original Range type didn't have different
semantics, if only to throw an exception when given an inverted range.
Cheers,
Ken
Daniel DeLorme wrote:
> Kenneth McDonald wrote:
>> Since a reverse range (eg. 4...1) is functionally almost the same as
>> an empty range, is there an alternative in the standard library,
>> where .each would actually iterate over the elements from first to
>> last, in this case 4, 3, 2?
>
> I can't resist this one...
>
> class Range
> def reverse
> r = dup
> def r.each(&block)
> last.downto(first, &block)
> end
> r
> end
> end
>
> >> (1..9).to_a
> => [1, 2, 3, 4, 5, 6, 7, 8, 9]
> >> (1..9).reverse.to_a
> => [9, 8, 7, 6, 5, 4, 3, 2, 1]
>
> :-D
>
> Daniel
>
>