June 2007
Intermediate to advanced
294 pages
8h 6m
English
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.
#!/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]))The get_lines method (❶) should look familiar at this point, since we’ve covered some very similar methods earlier in ...
Read now
Unlock full access