From: Christopher Swasey Date: 2008-03-02T07:42:53+09:00 Subject: Re: counting in for .. in .. On 3/1/08, Daniel Liebig wrote: > Hi, > > i'm doing my first steps in ruby (on rails) and often use things like > > for thing in @several_things > print thing > end > > Ok so far, looks great :) > > 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 > > Pardon me, but this is ugly, compared to the first clean lines. So far i > know ruby as an elegant language, so i wouldn't be surpised if there'd > be any kind of implemented counter in the for loop or a smarter way to > implement it. Simple. Use #each_with_index instead of for... in: @several_things.each_with_index do |thing, index| .... end Read up on Enumerable. It's pretty handy: http://www.ruby-doc.org/core/classes/Enumerable.html Christopher