#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 ...

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.