2013-07-03 34 views
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 (" ") 

因爲每個循環都告訴它重複,它是這樣做的,但是我怎麼能阻止它呢?

+0

請根據輸入添加輸入和輸出。 –

+0

在這裏重複'database_array'是否有任何理由? – tadman

+0

@tadman這可能是錯誤的複製粘貼,我想.. :) –

回答

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,如果你不熟悉的是,它基本上創建使用通過分隔字符串分隔陣列中的每個元素的字符串在我的例子中,這只是一個空白區域;替代你自己的課程,或者你想用它做的任何事情。

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 

輕微的修改,可以把它區分大小寫(如果需要的話),或添加單詞邊界的關鍵字,以不匹配部分單詞。

+0

這樣的短語謝謝幫助 – user2420858