Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Delete the last character in a file?

Tags:

file-io

ruby

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?

like image 375
Dylan Avatar asked Dec 31 '13 01:12

Dylan


People also ask

How do you remove the first and last character of a string in Ruby?

Use str[1.. -1], its fastest according to the answers below. As of Ruby 2.5 you can use delete_prefix and delete_prefix!

How do I remove a character from a string in Ruby?

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.


1 Answers

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.

like image 162
mu is too short Avatar answered Oct 19 '22 22:10

mu is too short