From: 7stud -- Date: 2008-03-02T14:39:47+09:00 Subject: Re: counting in for .. in .. Gregory Seidman wrote: > 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 > Rather that should be: arr = ['a', 'b', 'c'] arr.each_with_index do |elmt, i| puts "Element at index #{i} is: #{elmt}" end --output:-- Element at index 0 is: a Element at index 1 is: b Element at index 2 is: c -- Posted via http://www.ruby-forum.com/.