From: Rob Biedenharn Date: 2007-02-09T10:10:13+09:00 Subject: Re: Iterators and blocks question On Feb 8, 2007, at 7:05 PM, oinkoink wrote: > On Feb 8, 3:25 pm, "oinkoink" wrote: >> 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} > > Following up to myself, the idea is to keep from indenting the lines > differently > every time the line number passes a power of 10. > Regards, Bret width = (rl = IO.readlines("test.txt")).length.to_s.length format = "%2$#{width}d: %1$s" # see Kernel#sprintf rl.each_with_index { |*ary| ary[1] += 1; print format % ary } The ary[1]+=1 part is to make the numbers 1-based. If you're OK with the zero, leave it out. Of course, if you want to start with 1, it makes more sense to do: number = 0 rl.each { |line| number += 1; print format % [ line, number ] } or rl.each_with_index { |line,number| print format % [ line, number +1 ] } But then you could go back to the simpler format string and swap the order of the args yourself. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com