有单词列表和禁止单词列表。我想浏览一下单词表,并删除所有被禁止的单词。这就是我最终要做的(请注意catched
bool 值):
puts "Give input text:"
text = gets.chomp
puts "Give redacted word:"
redacted = gets.chomp
words = text.split(" ")
redacted = redacted.split(" ")
catched = false
words.each do |word|
redacted.each do |redacted_word|
if word == redacted_word
catched = true
print "REDACTED "
break
end
end
if catched == true
catched = false
else
print word + " "
end
end
有什么适当/有效的方法吗?
最佳答案
您可以使用 .reject
排除redacted
数组中存在的所有禁止的单词:
words.reject {|w| redacted.include? w}
Demo
如果要获取
words
数组中存在的禁止单词的列表,则可以使用 .select
:words.select {|w| redacted.include? w}
Demo