【问题标题】:Checking substrings in array and replacing them in ruby检查数组中的子字符串并在 ruby​​ 中替换它们
【发布时间】:2019-03-11 12:51:05
【问题描述】:

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

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"]

我不知道是什么方法可以做到这一点。

【问题讨论】:

  • 如何将“test_tweets”中匹配“banned_phrases”的单词替换为“CENSORED”?
  • 您要过滤,然后替换吗?过滤意味着删除,这使得替换没有意义。
  • 对不起,我的意思是替换

标签: arrays ruby string


【解决方案1】:

试试map + inject:

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

【讨论】:

    【解决方案2】:
    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."
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      相关资源
      最近更新 更多