Range weirdness

A

Alex Young

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?
 
T

Tomasz Wegrzanowski

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}


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].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,213
Messages
2,571,109
Members
47,702
Latest member
gancflex

Latest Threads

Top