首页 > 解决方案 > 检查数组中的子字符串并在 ruby​​ 中替换它们

问题描述

我被要求编写一个程序,将数组中与数组test_tweets中匹配的单词替换banned_phrases"CENSORED".

test_tweets = [
  "This politician sucks!",
  "I hate this Government!",
  "I can't believe we're living with such a bad politician. We were so foolish",
  "Politicianname is a danger to society. I hate that he's so bad – it sucks."
  ]

banned_phrases = ["sucks", "bad", "hate", "foolish", "danger to society"]

我无法弄清楚什么方法可以实现这一点。

标签: arraysrubystring

解决方案


尝试map+ inject

filtered = test_tweets.map do |tweet|
  banned_phrases.inject(tweet) do |r, phrase|
    r.gsub phrase, 'CENSORED'
  end
end

推荐阅读