新手:在我的情况下替换文本
在我的Ruby on Rails应用程序中,我的帮助程序中有一个方法,它通过以下方式打开文件:
content = File.open(myfile.txt)
该文件的内容如下:
my.car , my.seat, my.age; my.son , my.dog, my.chair; ...
所以,我将内容拆分为“ ; ”,如下所示:
content.split(';').each do |line| #Here, I want to replace the text from "my" to "her" on each line end
如何在内容中将每行“my”替换为“她”?
这是将内容更新为:
her.car , her.seat, her.age; her.son , her.dog, her.chair; ...
————————–更新———————– ———-
我想更新打开文件的内容 ,不仅在读取ruby代码中的内容时替换字符串。
无法动态修改文件的内容。 文件只能附加,不能展开,所以你不能用her
替换my
。
您可以从这个基本代码开始:
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")
虽然您可能希望使用正则表达式更具体,例如
line.gsub!(/\bmy\./, "her")