From: oinkoink Date: 2007-02-09T08:30:10+09:00 Subject: Re: Iterators and blocks question On Feb 8, 2:36 pm, Bharat Ruparel wrote: > IO.foreach("test.txt") {|line| puts line} > > This works great. However, I am trying to take the next step(s). For > starters, I would like to modify the above code such that it lets me > prepend the line numbers to each line as it is listed to the console. > Something similar to the listing below for example: > > 1. First line from the file.. > 2. Second line from the file... > . > . > 12. Last line from the file. > What is the Ruby idiom for doing this? Using the iterator and the code > block? > Thanks in advance. > Regards, > Bharat > Posted viahttp://www.ruby-forum.com/. Namaste Bharat. You might try something like require 'mathn' width = (Math.log((rl = IO.readlines("test.txt")).length)/ Math.log(10)).floor + 1 rl.each_with_index{ |line, k| print "%#{width}d. " % k + line} Regards, Bret