Prepend a single line to file with Ruby

MrDatabase picture MrDatabase · Dec 24, 2011 · Viewed 11.9k times · Source

I'd like to add a single line to the top a of file with Ruby like this:

# initial file contents
something
else

# file contents after prepending "hello" on its own line
hello
something
else

The following code just replaces the contents of the entire file:

f = File.new('myfile', 'w')
f.write "test string"

Answer

the Tin Man picture the Tin Man · Dec 24, 2011

This is a pretty common task:

original_file = './original_file'
new_file = original_file + '.new'

Set up the test:

File.open(original_file, 'w') do |fo|
  %w[something else].each { |w| fo.puts w }
end

This is the actual code:

File.open(new_file, 'w') do |fo|
  fo.puts 'hello'
  File.foreach(original_file) do |li|
    fo.puts li
  end
end

Rename the old file to something safe:

File.rename(original_file, original_file + '.old')
File.rename(new_file, original_file)

Show that it works:

puts `cat #{original_file}`
puts '---'
puts `cat #{original_file}.old`

Which outputs:

hello
something
else
---
something
else

You don't want to try to load the file completely into memory. That'll work until you get a file that is bigger than your RAM allocation, and the machine goes to a crawl, or worse, crashes.

Instead, read it line by line. Reading individual lines is still extremely fast, and is scalable. You'll have to have enough room on your drive to store the original and the temporary file.