如何阻止线条重复?

时间:2013-07-03 18:10:49

标签: ruby

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

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 (" ")

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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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的使用,如果你不熟悉它,它基本上使用传入的分隔符字符串分隔的数组中的每个元素创建一个字符串,在我的例子中它只是一个空格;当然可以替代你自己的,或者你想用它做什么。