我需要在gsub
括号中添加多个参数,但无论我尝试它,它似乎都不起作用。
# encoding: utf-8
# !/usr/bin/ruby
# create an empty array
original_contents = []
# open file to read and write
f = File.open("input.txt", "r")
# pass each line through the array
f.each_line do |line|
# push edited text to the array
original_contents << line.gsub(/[abc]/, '*')
end
f.close
new_file = File.new("output.txt", "r+")
new_file.puts(original_contents)
new_file.close
我需要它,所以我可以做很多不同的搜索和替换,如下所示:
original_contents << line.gsub(/[abc]/, '*' || /[def]/, '&' || /[ghi]/, '£')
当然我知道这段代码不起作用,但你明白了。我已尝试为每个参数使用数组,但最终会将文本多次打印到输出文件中。 有什么想法吗?
答案 0 :(得分:0)
正如Holger所说,我还建议您多次运行gsub
。将替换存储在哈希中,然后使用Enumerable#reduce
迭代地将它们应用于字符串时,可以使代码更漂亮。
replacements = {
/[abc]/ => '*',
/[def]/ => '&',
/[ghi]/ => '£'
}
f = File.open("input.txt", "r")
original_contents = f.lines.map do |line|
replacements.reduce(line) do |memo, (pat, replace)|
memo.gsub(pat, replace)
end
end
f.close
new_file = File.new("output.txt", "r+")
new_file.puts(original_contents)
new_file.close