[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Range weirdness

Alex Young

9/29/2006 4:00:00 PM

This surprised me:

C:\Documents and Settings\Alex>ruby -e "(4..1).each{|a| puts a}"

C:\Documents and Settings\Alex>ruby -e "(1..4).each{|a| puts a}"
1
2
3
4

C:\Documents and Settings\Alex>

Should it have done? I find it somewhat odd that ranges can only be
enumerated in one direction. Is there a reason for it?

--
Alex


1 Answer

Tomasz Wegrzanowski

9/29/2006 4:14:00 PM

0

On 9/29/06, Alex Young <alex@blackkettle.org> wrote:
> Should it have done? I find it somewhat odd that ranges can only be
> enumerated in one direction. Is there a reason for it?

There are many reason for it.

First, you need ranges with no elements.

Example:
> (0 .. x.size-1).each{|i| puts x[i]}

Now it works correctly with x=[]. It wouldn't if (0..-1) was 0.

Another example:
> x = ["a", "b", "c", "d"]
> p x[1..-2]
["b", "c"]

It wouldn't work either if (1..-2) meant [1,0,-1,-2].

--
Tomasz Wegrzanowski [ http://t-a-w.blo... ]