Ruby:gsub用文件

时间:2016-04-04 20:02:22

标签: ruby file replace gsub

所以我正在开发一个结合了不同配置文件的功能 我正在通过配置文件循环,当我看到一个特定的单词时(在此示例中,“Test”我希望将其替换为文件(多行文本)

我现在有这个

def self.configIncludes(config)
config = @configpath #path to config

combinedconfig = @configpath #for test purposes

doc = File.open(config)
text = doc.read
combinedConfig = text.gsub("test" , combinedconfig)
puts combinedConfig

所以现在我只用combineconfig替换我的字符串“test”,但是这个输出是我的配置所在的目录

如何用文字替换它? 所有帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

如果文件不大,您可以执行以下操作。

<强>代码

def replace_text(file_in, file_out, word_to_filename)
  File.write(file_out,
   File.read(file_in).gsub(Regexp.union(word_to_filename.keys)) { |word|
     File.read(word_to_filename[word]) })
end

word_to_filename是一个散列,使得密钥word将被名为word_to_filename[word]的文件的内容替换。

如果文件很大,请逐行执行此操作,也许使用IO#foreach

示例

file_in  = "input_file"
file_out = "output_file"
File.write(file_in, "Days of wine\n and roses")
  #=> 23
File.write("wine_replacement", "only darkness")
  #=> 13
File.write("roses_replacement", "no light")
  #=> 8
word_to_filename = { "wine"=>"wine_replacement", "roses"=>"roses_replacement" }

replace_text(file_in, file_out, word_to_filename)
  #=> 35
puts File.read(file_out)

Days of only darkness
 and no light

<强>解释

对于我在上例中使用的file_infile_outword_to_filename,步骤如下。

str0 = File.read(file_in)
  #=> "Days of wine\n and roses" 
r    = Regexp.union(word_to_filename.keys)
  #=> /wine|roses/

让我们先看看哪些字匹配正则表达式:

str0.scan(r)
  #=> ["wine", "roses"]

继续,

str1 = str0.gsub(r) { |word| File.read(word_to_filename[word]) }
  #=> "Days of only darkness\n and no light" 
File.write(file_out, str1)
  #=> 35 

在计算str1时,gsub首先匹配单词&#34; wine&#34;。因此,该字符串将传递给块并分配给块变量:

word = "wine"

并执行块计算:

str2 = word_to_filename[word]
  #=> word_to_filename["wine"]
  #=> "wine_replacement"
File.read("wine_replacement")
  #=> "only darkness"

so&#34; wine&#34;被替换为&#34;只有黑暗&#34;。玫瑰&#34;玫瑰花的比赛处理方式相似。