从句子中删除否定词

时间:2019-01-31 10:45:05

标签: ruby

下面的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."

1 个答案:

答案 0 :(得分:4)

您是否考虑过使用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