Arrays 检查数组中的子字符串并在ruby中替换它们

Arrays 检查数组中的子字符串并在ruby中替换它们,arrays,ruby,string,Arrays,Ruby,String,我被要求编写一个程序,将数组test_tweet中与禁用短语数组中的单词匹配的单词替换为censtered 我想不出是什么方法实现了这一点。试试map+inject: 产出是: [ "This politician CENSORED!", "I CENSORED this Government!", "I can't believe we're living with such a CENSORED politician. We were so CENSORED", "Polit

我被要求编写一个程序,将数组test_tweet中与禁用短语数组中的单词匹配的单词替换为censtered

我想不出是什么方法实现了这一点。

试试map+inject:

产出是:

[
  "This politician CENSORED!",
  "I CENSORED this Government!",
  "I can't believe we're living with such a CENSORED politician. We were so CENSORED",
  "Politicianname is a CENSORED. I CENSORED that he's so CENSORED – it CENSORED."
]

我如何将“test_tweets”中与“Banked_短语”匹配的单词替换为Censered?是否要筛选,然后替换?过滤意味着删除,这使得替换没有意义。对不起,我只是指替换
filtered = test_tweets.map do |tweet|
  banned_phrases.inject(tweet) do |r, phrase|
    r.gsub phrase, 'CENSORED'
  end
end
re = Regexp.union(banned_phrases)
# => /sucks|bad|hate|foolish|danger\ to\ society/
test_tweets.map{|s| s.gsub(re, "CENSORED")}
[
  "This politician CENSORED!",
  "I CENSORED this Government!",
  "I can't believe we're living with such a CENSORED politician. We were so CENSORED",
  "Politicianname is a CENSORED. I CENSORED that he's so CENSORED – it CENSORED."
]