查找并替换红宝石,除了一些短语文本文件
问题描述:
我很确定我错了。但我希望这个程序能够通过“phone_numbers.txt”运行,并取代除["Employee Marked Urgency as: low", "Employee Marked Urgency as: high"]
之外的任何重复内容。此代码的结果完全不是。没有改变。有小费吗?查找并替换红宝石,除了一些短语文本文件
file_names = ['phone_numbers.txt']
file_names.each do |file_name|
words_to_exclude = ["Employee Marked Urgency as: low", "Employee Marked Urgency as: high"]
text = File.read(file_name)
lines = text.split("\n")
new_contents = lines.uniq.reject do |word|
words_to_exclude.include? word
end.join("\n")
File.open(file_name, "w") { |file| file.puts new_contents }
end
答
我不知道我的理解是正确的,但使用Array#uniq
与块应该做的伎俩:
require 'digest/sha1' # to generate uniqs
file_names = ['phone_numbers.txt']
words_to_exclude = ["Employee Marked Urgency as: low",
"Employee Marked Urgency as: high"]
file_names.each do |file_name|
res = File.readlines(file_name).each_with_index.uniq do |s, idx|
words_to_exclude.include?(s) ?
Digest::SHA1.hexdigest(idx.to_s) : s
end.join("\n")
File.write(file_name, res)
end
这是怎么回事:如果我们从我们的名单中遇到的单词,我们生成无论如何,一个uniq足够的字符串是通过的;否则我们使用原始字符串进行比较。
如果您只需要某人查看您的代码,则应该在[代码评论](https://codereview.stackexchange.com/)上提出您的问题。如果您有任何问题,例如您的代码不符合您的要求,或者在运行时出现错误,请添加具体问题并提供详细信息。 – Mehraban