From: Jano Svitok Date: 2007-08-24T20:55:01+09:00 Subject: Re: How to append some data at the beginning of a file On 8/24/07, Ronald Fischer wrote: > > Thanks Ronald for your comments. I am wondering may be ruby > > got some way > > around it. > > It could, but I think it just happens too rare that someone > wants to do this. In more than 2 decades of programming, I > had this need only two or three times, for example. > > > newfile = File.new("test1","w") > > newfile.puts "This line should appear at the top of each file"; > > > > oldfile = File.open("test", "r+") > > oldfile.each_line { |line| newfile.puts line} > > oldfile.close(); > > or simply > > newfile.puts(File.read("test")) > > so you don't need the Ruby variable 'oldfile'. > > > newfile.close(); > > > > File.delete("test"); > > File.rename("test1", "test"); 1. it's better to use block form of File.open: File.open("test1","w") do |newfile| newfile.puts "This line should appear at the top of each file" File.open("test", "r+") do |oldfile| oldfile.each_line { |line| newfile.puts line} end end File.delete("test"); File.rename("test1", "test"); The difference is that in case of an exception the file is closed automatically. Otherwise you have to wait for garbage collector. It's a good habit to get used to this style. 2. newfile.puts(File.read("test")) will read the entire file into memory. Don't do this on large files - use the original way (or even better, loop over the file with File#read(size)). For small files, this read() is better. 3. newfile.puts(File.read("test")) will put an extra newline at the end. Use either newfile << File.read("test") or newfile.write(File.read("test"))