查找并替换除某些短语文本文件之外的ruby

时间:2017-11-11 05:42:46

标签: json ruby replace find repeat

我很确定我弄错了。但我希望这个程序运行“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

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解正确,但使用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足够的字符串让它无论如何都要通过;否则我们使用原始字符串进行比较。