2011-08-20 76 views
0

我正在通過編寫一個簡單的ChingChongCha程序來測試我的Ruby基礎知識。我的一種方法是將輸入的數據轉化爲數字(爲了將來在程序中易於使用),但如果這個語句保持默認爲'其他'條件,即使我能清楚地看到如果輸入了岩石與ROCK完美匹配。有任何想法嗎?如果在Ruby中不識別條件

def user_choice(choice) 
    # 1 is rock 
    # 2 is paper 
    # 3 is scissors 
    userintchoice = 0 
    choice.upcase! 

    # turns user's choice into an integer 
    puts choice #debugging 
    if (choice == 'ROCK') then 
    userintchoice = 1 
    elsif (choice == 'PAPER') then 
    userintchoice = 2 
    elsif (choice == 'SCISSORS') then 
    userintchoice = 3 
    else 
    puts "Invalid Choice!" 
    end 

    return userintchoice 

end 

代碼調用此方法並獲得輸入:

puts "What would you like to choose (input Rock, Paper or Scissors and <ENTER>)?" 
userstringchoice = gets() 
userchoice = user_choice(userstringchoice) 
+0

請發佈調用此函數的代碼,包括獲取用戶輸入的位置。 –

回答

3

看來你要調用.strip上userchoice,否則該字符串將包含一個尾隨\n

+0

哦,太棒了,甚至沒有想到這一點。它是固定的。非常感謝你的建議。我不習慣在Java中看到的東西。 – NickP