Read and write to files

Hi,

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.

File.open(“text.txt”, “r+”) do |file|
???
end

I am looking forward to hear from you.

King regards
Green E.

Perhaps you should break this down into 3 tasks to make it simpler for
you.

  1. Read the file

  2. Change the text

  3. Write a file

Thank you for your quickanswer, I have broken down my code in this three
steps.
But if anyone knows a solution for that, please tell me.

King regards
Green E.

Am 11.10.2013 22:02, schrieb Joel P.:

Perhaps you should break this down into 3 tasks to make it simpler for
you.

  1. Read the file

  2. Change the text

  3. Write a file

or

  1. read a line
  2. modify the line
  3. write (append) the line to a temporary file

and in both cases

  1. overwrite the old with the new file

Tempfile' andFileUtils’ from the Ruby stdlib might be very
useful here.

Regards,
Marcus

On Fri, Oct 11, 2013 at 10:24 PM, Green E. [email protected]
wrote:

Thank you for your quickanswer, I have broken down my code in this three
steps.
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.).

Kind regards

robert

Ok, thanks for your helpful answers, I will then change my code.

King regards
Green E.