On 2/19/07, Michael Brooks <michael.brooks / shaw.ca> wrote:
> Hello:
>
> I just started learning Ruby.  I like it's OOness however I've run
> across an unusual quirk with the "for loop" that.  The "for loop" can
> count up through a series of numbers, like so:
>
>    for number in (1..5)
>      puts number.to_s
>    end

for number in [5, 4, 3, 2, 1]
  puts number
end

(oh, note that puts calls .to_s already on its own ;)

for number in (1..5).to_a.reverse
  puts number
end

either is fine... however, it's not looking very nice... i really
would like to have ranges from top to bottom... not in this
ruby-version available though.

anyway, how is the syntax-highlighting different for for...end vs do...end?
and if you want matching highlighting, you can still do

5.downto(1) { |number|
  puts number
}

that matches the braces, it's the recommended syntax for oneliners though.
like that:

5.downto(1){ |number| puts number }

please note also that for is just syntactic sugar to make the
transition easier for programmers of other languages, what it
essentially does is:

(1..5).to_a.reverse.each do |number|
  puts number
end

hope i could help you with that a little
^ manveru

>
> which will output the digits 1 through 5.  However, the "for loop" does
> not appear to be able to count down when the range start and end is
> reversed, like so:
>
>    for number in (5..1)
>      puts number.to_s
>    end
>
> which outputs nothing.  I realize that using "downto" can get me what I
> want for down counting, like so:
>
>    5.downto(1) do |number|
>      puts number.to_s
>    end
>
> but I'd like to use the for because it's easier for me to see the start
> and end of the block (especially when using syntax highlighting editors
> like RDE).
>
> Can anyone help be understand why the "for loop" can't count down or if
> there is an alternative "for loop" syntax that I'm missing.
>
> Thank You,
>
> Michael
>
>