In my Ruby on Rails app, I have a method in my helper which opened a file by:
content = File.open(myfile.txt)
The cont
There is no way to modify the content of a file on the fly. Files can only be appended, they cannot be expanded, so you cannot replace my
with her
.
You can start from this basic code:
buf = ""
File.open('myfile.txt') do |file|
file.readlines.each do |line|
buf << line.gsub('my', "her")
end
end
File.open('myfile.txt', 'w') do |file|
file << buf
end
line.gsub!(/my/, "her")
Although you may want to get more specific with the regular expression, e.g.
line.gsub!(/\bmy\./, "her")