From: Niko Date: 2007-05-10T21:47:20+09:00 Subject: Re: loop questions Hi 5.times do |i| puts i end 0 1 2 3 4 1.upto(5) do |i| puts i end 1 2 3 4 5 5.downto(1) do |i| puts i end 5 4 3 2 1 Lloyd Linklater wrote: > I am new to ruby and loving it so far and have beginner's questions > about loops. > > I wanted something like this: > > for (int i = 1; i <= 5; i++) > printf("%d\n", [i]); > > expecting: > > 1 > 2 > 3 > 4 > 5 > > > I wrote this: > > i = 5 > > i.times do > puts i.to_s > end > > And got: > > 5 > 5 > 5 > 5 > 5 > > I am guessing that there is an internal variable that is incremented. > doh! Is there a way to get the changing variable in there without > having a separate variable in there? > > > Anyway, I then tried this: > > for i in 1..5 > puts i.to_s > end > > Which worked as expected. But I had better use for a descending loop. > In pascal it would be > > for i := 5 downto 1 do > writeln('%d', [i]); > > but I could not figure out how to do that in a for loop. I looked > through several books and could not find the answer. Any tips? > >