Newbie: text replacement in my case

前端 未结 2 1815
慢半拍i
慢半拍i 2021-01-27 06:49

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

2条回答
  •  执笔经年
    2021-01-27 07:10

    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
    

提交回复
热议问题