January 30, 2009 | In: Development
Reading One Line from a File in Ruby on Mac OS X
I recently needed to write a quick and dirty script in Ruby to generate 301 redirect lines in an .htaccess file for this site. The reason being I changed my permalink structure (ack!) and needed to clean up all the 404′s showing in Google’s Webmaster Tools.
The script simply reads in the report from Google, parses the pieces of each URL, creates the 301 redirect line, and writes it to a new file.
Simple right? Not on my mac!
Here’s the slimmed down code for simply reading a line from the file and printing it to stdout:
file = File.open("errors.csv", "r")
while line = file.gets
puts line
end
file.close
Straightforward? Check. Mind-numblingly simple? Check. Works as expected? NO!
The line while file.gets only executes once because it grabs the contents of the entire file without respecting newlines at all. I tried saving my file with every encoding and line ending format combination I had available in TextMate, but nothing worked.
So I finally gave up, decided to live with the fact that this file would always be small, and rewrote the code like this:
file = File.open("errors.csv", "r")
all_lines = file.read.split(/r?n|r(?!n)/)
for line in all_lines
puts line
end
file.close
And voila – it worked. Things like this drive me nuts. How can something as simple as reading one line from a file at a time cause so much frustration. I’ll figure out what was actually the cause of this at some point, but for now I’ve gotta get these 404′s cleaned up!

1 Response to Reading One Line from a File in Ruby on Mac OS X
Guillaume Lorrain-Belanger
October 3rd, 2011 at 9:12 pm
I encountered the same problem. Being new to Ruby, I first thought that there was a problem with my code. It took me a while to understand that things just weren’t working as expected. Quite frustrating.