F
F
Fenderas2014-09-11 11:07:23
ruby
Fenderas, 2014-09-11 11:07:23

How to correctly write lines in a text file?

Good afternoon. I use Ruby 2.1.2, OS FreeBSD 9.2. It is necessary to edit the text file, but I can’t do anything so that the changes are saved.
Now I'm using this code:

f = File.open("/tmp/test.conf", "a+")

f.each_line do |line|
  puts line.gsub!(/\/(.*)/, "99999")
end

f.close

The fact that the line is located and replaced, puts shows, but it's impossible to save the changes. After closing, the file has its original state.
Please put me on the right path :).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
s1dney, 2014-09-11
@s1dney

Your code opens the file for writing to the end of the file,
then changes each line by subline
and closes
but does not write anything to the file

V
vsuhachev, 2014-09-11
@vsuhachev

File.open("/tmp/test.conf", "r") do |in|
  File.open("/tmp/tmp_test.conf", "w") do |out|
    in.each_line { |line| out.puts line.gsub(/\/(.*)/, "99999") }
  end
end

In the general case, you cannot change something in the place in the file itself, you need to write the result to a new file. Rather, the replacement is possible byte to byte, and not like you have .*

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question