How to delete the last line of a file in Ruby?

I refer to the file, and before adding it, I want to delete the last line from the file. Is there an efficient way to do this in Ruby?

This is what I use to access the file:

file = File.new("imcs2.xml", "a")
+5
source share
3 answers

Assuming you want to delete the entire last line of the file, you can use this method, which determines the beginning of the last line and starts writing from there:

last_line = 0
file = File.open(filename, 'r+')
file.each {  last_line = file.pos unless file.eof? }

file.seek(last_line, IO::SEEK_SET)
#Write your own stuff here
file.close
+4
source

, , XML , , , , ruby, / XML. .

, Builder:

hpricot :

+6

The easiest way is to simply read the entire file, delete the "\ n" at the end, and overwrite it all with your own content:

filename = "imcs2.xml"
content = File.open(filename, "rb") { |io| io.read }
File.open(filename, "wb") { |io|
    io.print content.chomp
    io.print "yourstuff"    # Your Stuff Goes Here
}

Alternatively, simply io.seek () back along the last new line, if any:

filename = "imcs2.xml"
File.open(filename, "a") { |io|
    io.seek(-1, IO::SEEK_CUR)  # -1 for Linux, -2 for Windows: \n or \r\n
    io.print "yourstuff"    # Your Stuff Goes Here
}
+1
source

All Articles