Ruby: Adding line numbers to source code

Frequently I feel the need for putting line numbers in source files which I put up in my blogs so that I can refer to them in the discussion that follows.

 /*   1 */ using Output=System.Console;
/*   2 */
/*   3 */ namespace AbhinabaNameSpace
/*   4 */ {
/*   5 */     class HelloWorldMainClass
/*   6 */     {
/*   7 */         public static void Main()
/*   8 */         {
/*   9 */             Output.WriteLine("Hello World");
/*  10 */         }
/*  11 */     }
/*  12 */ }

I am sure there are tools that already do this, but like most programers I couldn't resist writing a small script to do it. I guess programers have re-invented the wheel so many times that they come in all shapes these days, including square, rectangular and linear :) I chose Ruby simply because I am learning it right now. To run this you need to have ruby installed on you system. Run ruby linenum.rb (without any params) to find out the usage.

 class LineNum
  def initialize(srcFile, destFile, startDelim, endDelim)
    raise ArgumentError.new("Source file #{srcFile} does not exist") unless File.exist?(srcFile)
    raise ArgumentError.new("Destination file #{destFile} already exist") if File.exist?(destFile)

    @srcFile = srcFile
    @destFile = destFile
    @startDelim = startDelim
    @endDelim = endDelim
  end

  def startCommenting()
    lineNum = 0
    outFile = File.open(@destFile, "w")
    File.open(@srcFile, "r").each_line { |line|
      lineNum += 1
      outFile.printf("%s %3d %s %s", @startDelim, lineNum, @endDelim, line)
    }
    outFile.close()
    puts("\nAdded line numbers to #{lineNum} lines")
  end
end

class Helper
  def Helper.showHelp
    puts "Usage: ruby lineNum <source file> <dest file> [<start delim> [<end delim>]]\n\n"
    puts "Example: ruby lineNum c:\\program.cs c:\\comment.cs\n"
    puts "         ruby lineNum c:\\program.cs c:\\comment.cs /* */\n"
  end
end

if ARGV.length < 2
  Helper.showHelp
else
  begin
    startDelim = "/*" #default start delims
    endDelim   = "*/" #default stop delims

    startDelim = ARGV[2] if ARGV.length > 2
    endDelim   = ARGV[3] if ARGV.length > 3

    lineNum = LineNum.new(ARGV[0], ARGV[1], startDelim, endDelim)
    lineNum.startCommenting()

  rescue
    $stderr.printf("Error!!! %s\n", $!)
  end
end