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.

···

--
Posted via http://www.ruby-forum.com/.

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

···

On 4/21/06, MenDAKE <mendake_ddude@yahoo.com> wrote:

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

···

--
Posted via http://www.ruby-forum.com/\.

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

···

--
Posted via http://www.ruby-forum.com/.

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

its not very ruby like. but it works

···

On 4/21/06, MenDAKE <mendake_ddude@yahoo.com> 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.

--
Posted via http://www.ruby-forum.com/\.

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

···

On 4/21/06, Guest <ath-admin@vt.edu> wrote:

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

--
Posted via http://www.ruby-forum.com/\.

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

<sarcasm>

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

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

</sarcasm>

Just playing with you a little.

- Jake McArthur

···

On Apr 22, 2006, at 11:36 AM, MenDAKE wrote:

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

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

···

On 4/21/06, Matthew Moss <matthew.moss.coder@gmail.com> wrote:

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

Matthew Moss wrote:

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

And if you like your "for" syntax:

for i in (1..8).reverse
  ...

Cheers,
Dave

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

···

On 4/21/06, Dave Burt <dave@burt.id.au> wrote:

Matthew Moss wrote:
> (1..8).reverse.each { |x| puts x }

And if you like your "for" syntax:

for i in (1..8).reverse
  ...