O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#10 Showing Line Numbers (line_num.rb)

Another useful trick when dealing with text files is the ability to automatically add line numbers to them. Here’s a script that does just that.

The Code

  #!/usr/bin/env ruby
  # line_num.rb

❶ def get_lines(filename)
    return File.open(filename, 'r').readlines
  end

❷ def get_format(lines)
    return "%0#{lines.size.to_s.size}d"    sprintf Formats
  end

❸ def get_output(lines)
    format = get_format(lines)
❹   output = ''    The each_with_index and sprintf Methods
❺   lines.each_with_index do |line,i|
❻     output += "#{sprintf(format, i+1)}: #{line}"
    end
    return output
  end

  print get_output(get_lines(ARGV[0]))

How It Works

The get_lines method (❶) should look familiar at this point, since we’ve covered some very similar methods earlier in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required