From: Rob Biedenharn Date: 2008-02-14T08:22:21+09:00 Subject: Re: my noob "numbering lines" programe. How to improve? On Feb 13, 2008, at 5:50 PM, Adam Akhtar wrote: > Give us hints on how to improve this program. If you want to show your > code off then go ahead but please give us the hints first i.e. what > methods you would use, what you would rewrite in my code etc. Its so > much better for me to go away and try and replicate your thinking than > just reading it. > > heres my version > > #program to insert numbers infront of lines. > def numbertext(infilename, outfilename) > #for neat formating work out how many lines there are first so we > know > how #many digits to set ljust to > totalnumlines = File.readlines(infilename).length > numdigits = 1 > x = 1 > while (x < totalnumlines) > x = x * 10 > numdigits = numdigits + 1 > end Since the representation of numbers doesn't shrink and you already have totalnumlines (which would typically be total_num_lines), perhaps you could think of a direct way of finding the number of character positions that you'd need to reserve for this largest number. > > linenumber = 0 > File.open(outfilename, "w") do |output| > File.foreach(infilename) do |input| Too bad you didn't save the lines when you read the file the first time... then you could have used .each_with_index. You could even use $. to get the current line number from the file rather than keep your own explicit counter in linenumber. (Which would be idiomatically line_number += 1) > > output.write linenumber.to_s.rjust(numdigits) + " " + input > linenumber = linenumber + 1 > end > end > end > -- All hints, no code. ;-) -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com