From: timr Date: 2009-05-02T04:10:07+09:00 Subject: Re: Read and re-write file with one open? On Apr 29, 9:27 pm, Adam Bender wrote: > [Note:  parts of this message were removed to make it a legal post.] > > I would like to write a Ruby script that opens a text file, performs a gsub > on each line, and then overwrites the file with the updated contents.  Right > now I open the file twice: once to read and once to write.  The reason for > this is that if I try to perform both operations on the same IO object by > calling io.rewind and writing from the beginning, and the substituted word > is shorter than what it is replacing, some portion of the end of the > original file remains.  Is there an idiom for "clearing" the contents of the > file before writing? > > Thanks, > > Adam I think File objects have a truncate method you can use after reading (f.truncate(0) #the file is now blank) to delete the contents. file.truncate(integer) => 0 Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms. f = File.new("out", "w") f.syswrite("1234567890") #=> 10 f.truncate(5) #=> 0 f.close() #=> nil File.size("out") #=> 5