0

看看这段代码。我得到了想要的结果,即扫描一个人的输入以查看它是否与内部数组匹配。

sentence = []
compare = []
database_array = ["Mouse", "killer", "Blood", "Vampires", "True Blood", "Immortal" ]

def parser_sentence compare
    database_array = ["Mouse", "killer", "Blood", "Vampires", "True Blood", "Immortal"]
    initial_index = 0
while compare.count > initial_index      
          compare.each do |item| 
         if item == database_array[initial_index]
            puts "You found the key word, it was #{item}"
          else
            puts "Sorry the key word was not inside your sentence"

          end
         end 
  initial_index = initial_index + 1
 end
end

puts "Please enter in your sentences of words and i will parse it for the key word."
sentence = gets.chomp
compare = sentence.split (" ")

因为每个循环都在告诉它重复,所以它会这样做,但是我怎样才能阻止它呢?

4

2 回答 2

2

在这种情况下,正则表达式将比拆分输入字符串更有效且更不容易出错,特别是因为您在关键字列表中有一个两个单词的短语。

def parser_sentence(sentence)
  matching_words = sentence.scan(Regexp.union(database_array))
  if matching_words.empty?
    puts "Sorry the key word was not inside your sentence"
  else
    puts "You found the key word, it was #{matching_words.join(" ")}"
  end
end

稍作修改可以使其区分大小写(如果需要),或为关键字添加单词边界以不匹配部分单词。

于 2013-07-03T19:02:05.200 回答
1

一种不涉及循环的可能解决方案是与您的comparedatabase_array数组相交,如下所示:

matching_words = compare & database_array

这将比较两个数组并创建一个新数组,其中仅包含两者共有的元素。例如:

# If the user input the sentence "The Mouse is Immortal", then...
compare = ["The", "Mouse", "is", "Immortal"]
# matching_words will contain an array with elements ["Mouse", "Immortal"]
matching_words = compare & database_array

然后,您可以检查数组的长度并显示您的消息。我相信这可以像这样替换您的整个功能:

def parser_sentence compare
    matching_words = compare & database_array
    if matching_works.length > 0
        puts "You found the key word, it was #{matching_words.join(" ")}"
    else
        puts "Sorry the key word was not inside your sentence"
    end
end

请注意使用join,如果您不熟悉它,它基本上使用数组中的每个元素创建一个字符串,这些元素由传入的分隔符字符串分隔,在我的示例中只是一个空格;代替你自己的当然,或者你想用它做什么。

于 2013-07-03T18:43:26.587 回答