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


#1

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.


#2

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| … }


#3

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


#4

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


#5

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


#6

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


#7

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

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


#9

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


#10

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

its not very ruby like. but it works


#11

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