Ruby - Delete the last character in a file?

There is File.truncate:

truncate(file_name, integer) → 0

Truncates the file file_name to be at most integer bytes long. Not available on all platforms.

So you can say things like:

File.truncate(file_name, File.size(file_name) - 1)

That should truncate the file with a single system call to adjust the file's size in the file system without copying anything.

Note that not available on all platforms caveat though. File.truncate should be available on anything unixy (such as Linux or OSX), I can't say anything useful about Windows support.


I assume you are referring to a text file. The usual way of changing such is to read it, make the changes, then write a new file:

  text = File.read(in_fname)
  File.write(out_fname, text[0..-2])

Insert the name of the file you are reading from for in_fname and the name of the file you are writing to for 'out_fname'. They can be the same file, but if that's the intent it's safer to write to a temporary file, copy the temporary file to the original file then delete the temporary file. That way, if something goes wrong before the operations are completed, you will probably still have either the original or temporary file. text[0..-2] is a string comprised of all characters read except for the last one. You could alternatively do this:

  File.write(out_fname, File.read(in_fname, File.stat(in_fname).size-1))

Tags:

Ruby

File Io