Newbie: text replacement in my case

前端 未结 2 1814
慢半拍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
    
    0 讨论(0)
  • 2021-01-27 07:11
    line.gsub!(/my/, "her")
    

    Although you may want to get more specific with the regular expression, e.g.

    line.gsub!(/\bmy\./, "her")
    
    0 讨论(0)
提交回复
热议问题