Robert Klemme
5/10/2007 12:46:00 PM
On 10.05.2007 14:33, 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?
The current value us passed to the block. So rather do
5.times do |i|
puts i
end
> Anyway, I then tried this:
>
> for i in 1..5
> puts i.to_s
> end
You don't need the to_s here as puts will do that automatically.
> 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?
5.downto 1 do |i|
puts i
end
or
5.step 1, -1 do |i|
puts i
end
If you think you need a /for/ loop:
for i in (1..5).to_a.reverse
puts i
end
But I'd rather not do this.
Kind regards
robert