【问题标题】:Find and replace ruby except some phrases text file查找和替换除某些短语文本文件外的 ruby
【发布时间】:2017-11-11 14:39:31
【问题描述】:

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

【问题讨论】:

  • 如果您只需要有人检查您的代码,您应该在code review 上提问。如果您有任何问题,例如为什么您的代码不符合您的要求,或者您在运行时遇到错误,请添加该特定问题的详细信息。

标签: json ruby replace find repeat


【解决方案1】:

我不确定我是否理解正确,但是使用带有块的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 足够的字符串以让其通过;否则我们使用原始字符串进行比较。

【讨论】:

  • 我认为你的代码有错误。我尝试运行它,但它只返回一个错误
  • ``
    中的块':未定义方法with_index' for #<Array:0x007ff0cf175760> (NoMethodError)
  • 我手头没有文件,所以无法测试这个,但我相信你有一个很好的起点。
  • 啊,对不起,错字。应该是each_with_index
  • 啊! ``block in
    ': 未定义方法uniq!' for "#<Enumerator:0x007ff028184cf8>":String (NoMethodError)
猜你喜欢
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2014-07-05
  • 2013-04-06
  • 2017-01-10
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多