Newbie: text replacement in my case

安稳与你 提交于 2019-12-04 06:05:54

问题


In my Ruby on Rails app, I have a method in my helper which opened a file by:

content = File.open(myfile.txt)

The content of the file is like:

my.car , my.seat, my.age;
my.son , my.dog, my.chair;
...

So, I split the content by ";" like following:

content.split(';').each do |line|
      #Here, I want to replace the text from "my" to "her" on each line
end

How to replace each line's "my" to "her" in the content?

that's to update content to:

her.car , her.seat, her.age;
her.son , her.dog, her.chair;
...

-------------------------- update ---------------------------------

I would like to update the content of the opened file , not only replace the string when read the content from the ruby code.


回答1:


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



回答2:


line.gsub!(/my/, "her")

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

line.gsub!(/\bmy\./, "her")


来源:https://stackoverflow.com/questions/7965199/newbie-text-replacement-in-my-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!