新手:在我的情况下文本替换 [英] Newbie: text replacement in my case
本文介绍了新手:在我的情况下文本替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的 Ruby on Rails 应用程序中,我的助手中有一个方法可以通过以下方式打开文件:
In my Ruby on Rails app, I have a method in my helper which opened a file by:
content = File.open(myfile.txt)
文件内容如下:
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
如何将内容中每一行的我的"替换为她的"?
即更新内容:
her.car , her.seat, her.age;
her.son , her.dog, her.chair;
...
-------------------------- 更新---------------------------------
我想更新打开文件的内容,而不只是在从ruby代码读取内容时替换字符串.
I would like to update the content of the opened file , not only replace the string when read the content from the ruby code.
推荐答案
没有办法动态修改文件内容.文件只能追加,不能扩展,所以你不能用her
替换my
.
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
这篇关于新手:在我的情况下文本替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文