From: William James Date: 2008-03-02T14:54:54+09:00 Subject: Re: counting in for .. in .. William James wrote: > On Mar 1, 4: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 > > > > 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. > > > > > E:\>irb --prompt xmp > a = %w(zero one two three) > ==>["zero", "one", "two", "three"] > a.each_with_index{|x,i| puts "Item no. #{i} is #{x}."} > Item no. 0 is zero. > Item no. 1 is one. > Item no. 2 is two. > Item no. 3 is three. > ==>["zero", "one", "two", "three"] puts a.zip((0...a.size).to_a).map{|a| "Item #{a[1]} is #{a[0]}"} Item 0 is zero Item 1 is one Item 2 is two Item 3 is three