Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't backward for loop work in ruby? eg. for i in 10..1 [duplicate]

Tags:

range

ruby

Possible Duplicate:
Is there a reason that we cannot iterate on “reverse Range” in ruby?

This works like magic.

for i in 1..10
  ...
end

Isn't it only intuitive that this backward for loop should work as well?

for i in 10..1
  ...
end

If there is some syntactical reason why this shouldn't work, I feel like ruby has to be changed to allow it. It's just intuitive to write backward for loop that way.

like image 791
Jason Kim Avatar asked Oct 09 '11 17:10

Jason Kim


2 Answers

try something like

10.downto(1) { |i| ... }
like image 138
Jason Avatar answered Sep 28 '22 03:09

Jason


1..10 is of class Range, not directly linked with any loop constructs. And there are no numbers that are both bigger than 10 and smaller than 1, therefore the range 10..1 is empty.

PS I don't recall when was the last time I wrote a for loop in ruby. Maybe something from http://www.ruby-doc.org/core-1.9.2/Enumerable.html would serve you better?

like image 42
Toms Mikoss Avatar answered Sep 28 '22 02:09

Toms Mikoss