Paste text into an existing file

I have a txt file. How can I put some text in it and not overwrite it? because when I use for example f.puts "aaaaaaaaaaaaaaa", Ruby overwrites my txt file. thank

+5
source share
3 answers

If you ask how to embed text in the middle of an existing file, as shown below, you cannot:

Original file first half, Original File second half

becomes:

Original file first half, Inserted text, Original File second half

You need to create a new file, copy the first half of the original into it, then write new text, and then copy the remaining source file.

+4
source

You need to open it in add mode

File.open("file.txt", "a+"){|f| f << "aaaaaaaaaaaaaaaaaaa" }

Check your previous question

File Open Mode in Ruby

+16

All Articles