2016-07-30 71 views
0

我不能與此代碼找出問題:while循環不起作用。包括串並轉換爲大寫

select = false 
while (!select) 
    print "What animal do you want to adopt? (Cat/Dog/Fish): " 
    your_animal = gets 
    if your_animal.upcase == "CAT" or your_animal.upcase == "DOG" or your_animal.upcase == "FISH" 
    puts "Ah, you want #{your_animal}." 
    select = true 
    else 
    puts "Please pick from any of the three animals and make sure it is spelled correctly." 
    end 
end 

if語句三個條件不工作,並在else聲明甚至會執行代碼如果我寫入要激活的if語句的正確響應。

任何幫助,將不勝感激。

回答

3

變化

your_animal = gets 

your_animal = gets.chomp 

其原因是gets返回整個字符串輸入,包括終止回車

旁註:不是

your_animal.upcase == "CAT" or 
    your_animal.upcase == "DOG" or 
    your_animal.upcase == "FISH" 

一個可以使用:

%w(CAT DOG FISH).include? your_animal.upcase 
+0

...和'直到(選擇)',而不是',而(!選擇)'。另外,如果你打算把'gets'的結果轉換爲一個整數(不在這裏),你可以寫'gets.chomp.to_i'或者'gets.to_i',因爲'to_i'儘快終止轉換因爲它擊中了一個數字以外的字符(或字符串的結尾)。與'to_f'相同。 –

+0

完美的工作!在你提到這個之後我讀了它,我明白爲什麼;因爲當你輸入一個字符時,例如: 「CAT 」 這與「CAT」不一樣。 謝謝,這非常有道理! –

+0

Alex,不,'gets'返回''CAT \ n「'。 –