首页 > 解决方案 > 从句子中删除否定词

问题描述

下面的neutralize方法旨在从句子中删除否定词。

def neutralize(sentence)
  words = sentence.split(' ')
  words.each do |word|
    words.delete(word) if negative?(word)
  end
  words.join(' ')
end

def negative?(word)
  [
    'dull',
    'boring',
    'annoying',
    'chaotic'
  ].include?(word)
end

但是,它无法删除所有这些。而我希望得到:

"These cards are part of a board game."

我得到以下结果:

neutralize('These dull boring cards are part of a chaotic board game.')
# => "These boring cards are part of a board game."

标签: ruby

解决方案


你考虑过使用delete_if吗?

def neutralize(sentence)
  words = sentence.split(' ')
  words.delete_if { |word| negative? word }
  words.join(' ')
end

def negative?(word)
  [ 'dull', 'boring', 'annoying', 'chaotic' ].include? word
end

puts neutralize('These dull boring cards are part of a chaotic board game.')

修改您正在迭代的数组可能会导致问题。例如:

a = [1, 2, 3, 4]
a.each { |i| a.delete i }
p a
# => [2, 4]

在大多数情况下,您应该避免它。

为了更好地理解为什么输出是这样的,请看这个例子:

a = [1, 2, 3, 4, 5, 6]
a.each_with_index do |item, index|
  puts "deleting item #{item} at index #{index}:"
  a.delete item
  p a
end

推荐阅读