Say I have a file.txt
that contains, among other things, a line that is Value=50
. I don't know for sure the number of the line because the contents of the file may vary. At some point on my code, I want to change this line, replace it with, say, Value=30
. I have a code for this already, but I can't figure out how to replace instead of adding another line.
My current code:
f = File.open('file.txt', 'r+')
f.any? do |line|
if line.include?("Value")
num = line.split('=').last
newNum = 30
line = line.gsub(/#{vol}/, newNum.to_s)
f.write(line)
end
end
f.close
And the file.txt
would be something like
foo
fooooo
Value=50
foo
It works great, but instead of replacing the old Value=
line, it just adds a new one, sometimes in front and sometimes below it. I've already tried just leaving the line.gsub()
part, but it made no changes to the file. I've tried f.puts(line)
too, but if I remember correctly it would just add a new line.
I'm using this code in RPG Maker, so I'd like to solve this without libraries like Fileutils, unless they're extremely necessary.