Seems like it must be easy, but I just can't figure it out. How do you delete the very last character of a file using Ruby IO?
I took a look at the answer for deleting the last line of a file with Ruby but didn't fully understand it, and there must be a simpler way.
Any help?
Use str[1.. -1], its fastest according to the answers below. As of Ruby 2.5 you can use delete_prefix and delete_prefix!
In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.
There is File.truncate
:
truncate(file_name, integer) → 0
Truncates the file
file_name
to be at mostinteger
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With