I want to open a file and then I want to read the first the line, play a
bit with it and give a changed line to the same place back. I tried it
with for each_line etc. or while line = gets but I all does not work. I
always get the error that I called puts which is a private method. But I
am using r+ and so on.
Thank you for your quickanswer, I have broken down my code in this three
But if anyone knows a solution for that, please tell me.
A general solution for in place line exchange is tricky to do
efficiently: since the replacement line can be shorter or longer than
the original line all the data after that line in the file needs to be
moved. And since on changing one line nobody knows how other lines
may change it is not possible to optimize data moving (i.e. move all
lines to the location they will be eventually if the whole file has
been processed). Given that, the most efficient solution is really to
do like Joel suggested or write a second file and rename it to the
original file after processing has been completed. Note that Joel’s
approach will avoid the second file at the cost of storing the
temporary file contents in memory. There will be a limit on the size
of file where that approach works well. That limit of course depends
on your environment (memory, load on the system etc.).