How to delete last line of file in Ruby?

file, ruby

Solution

Assuming you want to remove the entire last line of the file, you can use this method which locates the start of the last line and begins 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

Problem

I am accessing a file, and before I append to it, I want to delete the last line from the file. Is there any efficient way of doing this in Ruby? This is what I am using to access the file: ``` file = File.new("imcs2.xml", "a") ```

Original source