Range weirdness

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?

On 9/29/06, Alex Y. [email protected] 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].

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs