Newbie questoin of the day:A for loop that counts backwards?

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 [email protected] 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

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

Ooops, one too many periods. That should be: (1…8)

Not me… “for” can go hang out in my C++ code with the other schmuck
keywords.

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

8.downto(1) {|x| puts x}

Wow, so many options. What a great language. Thanks, everyone.

max=9
for i in 1…8
p max-i
end

its not very ruby like. but it works

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