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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
MenDAKE (Guest)
on 2006-04-21 23:23
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.
Gregory B. (Guest)
on 2006-04-21 23:29
(Received via mailing list)
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| ... }
Guest (Guest)
on 2006-04-22 00:41
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. (Guest)
on 2006-04-22 00:52
(Received via mailing list)
(1...8).reverse.each { |x| puts x }
Matthew M. (Guest)
on 2006-04-22 00:52
(Received via mailing list)
Ooops, one too many periods.  That should be:  (1..8)
Dave B. (Guest)
on 2006-04-22 01:48
(Received via mailing list)
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
Matthew M. (Guest)
on 2006-04-22 02:04
(Received via mailing list)
Not me...  "for" can go hang out in my C++ code with the other schmuck
keywords.
Farrel L. (Guest)
on 2006-04-22 02:10
(Received via mailing list)
8.downto(1) {|x| puts x}
MenDAKE (Guest)
on 2006-04-22 20:36
Wow, so many options. What a great language. Thanks, everyone.
ruby talk (Guest)
on 2006-04-22 21:01
(Received via mailing list)
max=9
for i in 1..8
p max-i
end


its not very ruby like. but it works
Jake McArthur (Guest)
on 2006-04-23 02:11
(Received via mailing list)
<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
This topic is locked and can not be replied to.