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 Eco

···

--
Posted via http://www.ruby-forum.com/.

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

···

--
Posted via http://www.ruby-forum.com/.

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 Eco

···

--
Posted via http://www.ruby-forum.com/.

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

King regards
Green Eco

···

--
Posted via http://www.ruby-forum.com/.

or

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

and in both cases

4) overwrite the old with the new file

`Tempfile' and `FileUtils' from the Ruby stdlib might be very
useful here.

Regards,
Marcus

···

Am 11.10.2013 22:02, schrieb Joel Pearson:

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

--
GitHub: stomar (Marcus Stollsteimer) · GitHub
PGP: 0x6B3A101A

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

···

On Fri, Oct 11, 2013 at 10:24 PM, Green Eco <lists@ruby-forum.com> 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.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/