How do I get a for loop to count backwards?

I have the loop…

for i in 1 … 8

…but I want it to start at 8 and end at 1. This does NOT work:

for i in 8 … 1

Thanks for helping out a newbie.

How do I get a for loop to count backwards?

I have the loop…

for i in 1 … 8

…but I want it to start at 8 and end at 1. This does NOT work:

for i in 8 … 1

Thanks for helping out a newbie.

On 4/21/06, MenDAKE removed_email_address@domain.invalid wrote:

How do I get a for loop to count backwards?

I have the loop…

for i in 1 … 8

1.upto(8) { |i| … }

…but I want it to start at 8 and end at 1. This does NOT work:

for i in 8 … 1

8.downto(1) { |i| … }

MenDAKE wrote:

How do I get a for loop to count backwards?

I have the loop…

for i in 1 … 8

…but I want it to start at 8 and end at 1. This does NOT work:

for i in 8 … 1

Thanks for helping out a newbie.

I like doing it this way… it makes more sense to me:

x = 8

while x > 0

x = x-1

puts x

end

Matthew M. wrote:

(1…8).reverse.each { |x| puts x }

And if you like your “for” syntax:

for i in (1…8).reverse

…

Cheers,

Dave

def countdown(from, to)

yield from

countdown(from-1, to) { |x| yield x } if from > to

end

countdown(8, 1) { |x| puts x }

Just playing with you a little.

- Jake McArthur