在文件中的数组中查找错误的单词,然后将其替换为***

时间:2015-06-10 03:24:22

标签: ruby

我是红宝石的新手, 我有一堆坏词,所以我想测试一个文件,如果发现一个坏词然后用***替换它

class BadWord
  def changeword
    bad_word = [ "badword1", "badword2", "badword3", "badword4" ]
    data = File.read("script.txt")
    filterdata = bad_word.map{|item|
    data.gsub("#{item}","***")
    File.write("script.txt",filterdata)
  end
end
obj = BadWord.new()
obj.changeword()

1 个答案:

答案 0 :(得分:2)

我会做这样的事情:

class BadWordsFilter < Struct(:filename)
  attr_reader :filename

  BAD_WORDS   = w%[badword1 badword2 badword3 badword4]
  WORD_REGEXP = Regexp.union(BAD_WORDS)

  def sanitize
    content  = File.read(filename)
    filtered = content.gsub(WORD_REGEXP, '***')

    File.write(filename, filtered)
  end
end

filter = BadWordsFilter.new('script.txt')
filter.sanitize