On Sun, Mar 02, 2008 at 07:24:34AM +0900, Daniel Liebig wrote:
> i'm doing my first steps in ruby (on rails) and often use things like
> 
> for thing in @several_things
>   print thing
> end
[...]

For reasons I find it difficult to express the for-in construct is frowned
upon. There are better and more flexible iteration constructs, and it looks
like you are starting to feel the need for them.

> But i often need a counter inside of the loop, may it be to create row
> colors or other stuff. What i end up with then is:
> 
> i = 0
> for thing in @several_things
>   print thing + " No. " + i.to_s
>   i += 1
> end
[...]

This is where each_with_index, one of those more flexible iteration
constructs, comes in.

@several_thing.each_with_index do |thing,i|
   print thing + " No. " + i.to_s
   i += 1
end

You should be familiar with ri for reading Ruby API documentation. Look up
Enumerable for the wide variety of iteration/enumeration constructs Ruby
gives you right out of the box. There are even more advanced constructs
available from other libraries (e.g. facets).

> Thanks a lot for any help!
> R.D.
--Greg