From: Jano Svitok Date: 2008-03-02T07:38:44+09:00 Subject: Re: counting in for .. in .. On Sat, Mar 1, 2008 at 11:24 PM, 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 Let's start with equivalent code: @several_things.each do |thing| 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 Now let me introduce Enumerable module, that contains each_with_index: @several_things.each_with_index do |thing, i| print "#{thing} No. #{i}" end Note: #{expression} is replaced with expression.to_s (more or less) Lookup Enumerable in the docs, it contains lots of useful stuff. > 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. > > Any hints? > > Thanks a lot for any help! > R.D. > -- > Posted via http://www.ruby-forum.com/. > >