arrays - 检查数组中的子字符串并在 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"]
我无法弄清楚什么方法可以实现这一点。
解决方案
尝试map
+ inject
:
filtered = test_tweets.map do |tweet|
banned_phrases.inject(tweet) do |r, phrase|
r.gsub phrase, 'CENSORED'
end
end
推荐阅读
- php - Wordpress 页面上的自定义搜索查询不起作用
- tensorflow - 手动绘制边界框时的问题
- matlab - 使用 linspace 时出错(第 22 行)输入必须是标量
- python - 如何从数据框行中的字典中提取值
- html - 为什么我有幽灵边距?
- tabulate - ModuleNotFoundError:没有名为“制表”的模块
- javascript - 无法将项目推入 React Js 中的列表
- python - 如何从 Python Lambda 函数中访问 TaskToken
- algorithm - 拓扑排序和汉密尔顿路径?
- vba - E_ACCESSDENIED "General Access denied error" /CreateObject("Vbscript") 在 office 365 VBA 环境下被阻止