用Ruby替换txt文件中的字符串

时间:2014-09-02 18:10:17

标签: ruby

我是红宝石的新手。我试图使用Ruby在同一文本文件中保存更改。我该如何处理?

这就是我的尝试:

f = File.open("D:/test.txt", "r")
oldcolor = "white"
newcolor = "black"
f.each_line do |line|
  line.sub(oldcolor,newcolor)
  puts line
end
f.close

有关如何在sub中使用变量而不是正则表达式的任何建议,或者可能是将“白色”替换为“黑色”的任何其他方法?

3 个答案:

答案 0 :(得分:1)

您需要做的是:

f = File.open("D:/test.txt", "r")
oldcolor = "white"
newcolor = "black"
newfile_str = ""
f.each_line do |line|
  newfile_str += line.sub(oldcolor,newcolor)
end
f.close
File.open("D:/test.txt", "w") {|file| file.puts newfile_str}

有更简单的方式this,但我想使用您自己的代码让您更容易理解。

说明: 我将修改后的行存储在一个字符串中,然后将其写入文件。

答案 1 :(得分:1)

我认为@ ShaneQful的回复是好的,因为它使用了你的代码,但你可以按照他说的那样使用

更容易
file_name = "D:/test.txt"
old_color = "white"
new_color = "black"
File.write(file_name,File.open(file_name,&:read).gsub(old_color,new_color))

它的作用是打开file_name将其读入字符串。用[{1}}替换#gsub的所有实例(old_color),然后将其写回new_color

简单,简单,干净,简洁。

更新

file_nameFile#readFile.open(file_name,&:read)的基准测试(如ShaneQful'示例中所示)

这是针对杰克伦敦的白方的基准,其中包含约75,000个单词和645个单词File.open with block read into a string and then written back to file_name的实例

white

似乎#Benchmark Rehearsal -------------------------------------------------------- File#read 0.375000 0.484000 0.859000 ( 1.462000) File.open(&:read) 0.437000 0.530000 0.967000 ( 1.480000) File.open with block 1.404000 0.359000 1.763000 ( 2.150000) ----------------------------------------------- total: 3.589000sec user system total real File#read 0.452000 0.499000 0.951000 ( 1.401000) File.open(&:read) 0.483000 0.421000 0.904000 ( 1.445000) File.open with block 1.529000 0.328000 1.857000 ( 2.120000) #Fruity Running each test 2 times. Test will take about 3 minutes. File.open(&:read) is similar to File#read File#read is faster than File.open with block by 50.0% ± 10.0% File#read来回交换实现的速度,但是对于这类事情,使用真正的块来处理相同的操作总是要慢得多。

使用File.open(file_name,&:read)read#open(file_name,&:read))这样的简单程序的概要。如果您需要执行可能需要多行或条件选项的精细更改,那么我将使用块

答案 2 :(得分:1)

  

我是红宝石的新手。我想在同一文本文件中保存更改   使用红宝石。

出于所有实际目的,你不能,而且你真的不想 - 无论如何。而是写入新文件,删除旧文件,将新文件重命名为旧文件名。

相关问题