On Sep 26, 2007, at 10:23 PM, blufur wrote:

> how can my ruby program tell me how many lines are in a text file?

Probably the easiest code for this is:

   line_count = 0
   File.foreach(?) { line_count = $. }

That's not too great performance-wise on huge files though.  We can  
optimize the reads to speed it up a little:

   line_count = 0
   File.open(ARGV.shift) do |f|
     while block = f.read(1024)
       line_count += block.count("\n")
     end
   end

That version is more than twice as fast on the 96 MB file I tried it on.

> how can i have my ruby program edit the last line of a text file  
> (not add another line at the end, but get and then change the line  
> at the end).

   Firefly:~/Desktop$ cat edit_last_line.rb
   #!/usr/bin/env ruby -wKU

   require "rubygems"
   require "elif"

   file = ARGV.shift

   # read the last line
   last_line = Elif.open(file) { |f| f.gets }

   # remove it from the file
   File.truncate(file, File.size(file) - last_line.size)

   # replace the line
   File.open(file, "a") { |f| f.puts last_line.sub(/\blazy\b/,  
"sleeping") }

   __END__
   Firefly:~/Desktop$ cat data.txt
   The quick brown fox
   jumped over
   the lazy dog.
   Firefly:~/Desktop$ ruby edit_last_line.rb data.txt
   Firefly:~/Desktop$ cat data.txt
   The quick brown fox
   jumped over
   the sleeping dog.

Hope that helps.

James Edward Gray II