Decending Range

D

Dominic Marks

Hello,

I was surprised of to find this behaviour:

irb(main):008:0> a, b = 1, 100
=> [1, 100]
irb(main):009:0> (a..b).to_a.length
=> 100
irb(main):010:0> (b..a).to_a.length
=> 0

Now I am aware that only a simple .reverse is required to work
around this but this seemed a little un-ruby like. Is there
some thoughtful reason to not have ranges in both
directions that I'm missing?

Cheers,
Dominic
 
C

come

Hi,

That's normal since backward ranges cannot be iterated. They have no
size. Just boundaries, so you can still use them for other purposes,
though. For instance when one side of the range should reference a
string from the end : string=hello string[0..-1] => "hello".

If (0..-1) would have been {0, -1}, then string[0..-1] => "ho". Not
very usefull. Maybe the reason is just because backward ranges are
more usefull in the first way.

Come.
 
D

dblack

Hi --

Ranges can be constructed using objects of any type, as long as the objects
can be compared using their <=> operator and they support the succ method to
return the next object in sequence.

That's actually not a necessary condition -- you can have a range of
floats too. A range is fundamentally a kind of boolean test filter
for inclusion, and only secondarily a sort of ersatz array. I tend to
think too much is sometimes expected of ranges in the latter role.


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 

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

No members online now.

Forum statistics

Threads
473,813
Messages
2,569,696
Members
45,480
Latest member
CrazyMember

Latest Threads

Top