2013-07-03 8 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

이 경우 정규식은 입력 문자열을 분할하는 것보다 효율적이며 덜 오류가 발생합니다. 특히 키워드 목록에 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

관련 문제