2012-09-28 120 views
0

我無法讓該程序正確響應用戶輸入。各種循環技術或者只運行一次塊或者無限次地運行塊,無論用戶輸入什麼(我也試過casewhile)。下面是最新的方法我試過:爲什麼我的循環不工作?

work_summary = [] 
begin 
    # code that runs a sprint and adds results to the work_summary array 
    puts "Would you like to add a sprint, Y/N?" 
    sprint = gets.to_s 
end until sprint == "N" 
print work_summary, "\n" 

紅寶石從來沒有反對我的任何的各種方法的語法,但它也永遠不會奏效。

回答

5

需要

sprint = gets.chomp 

獲取返回字符串尾隨 「\ n」 個。

+0

謝謝,@UncleGene - 就是這樣。 –

3

http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#begin

開始通常用於異常處理。我想你正在尋找一個while循環。

下面是一個例子 work_summary = []

while true 
    puts "Would you like to add a sprint?" 
    sprint = gets.chomp 
    if sprint == "N" 
    break 
    elsif sprint == "Y" 
    puts "What's your time?" 
    time = gets.chomp 
    work_summary << time 
    else 
    puts "I didn't understand your request. Enter Y or N" 
    end 
end 
+0

謝謝 - 當'while'沒有工作時,我訴諸'開始',但我會切換回'while'現在我知道什麼問題。 –

2

我發現在這裏有兩個可能性,你

第一個是

while true 
    puts "Would you like to add a sprint?" 
    sprint = gets.chomp 
    if sprint == "N" 
    break 
    elsif sprint == "Y" 
    puts "What's your time?" 
    time = gets.chomp 
    work_summary << time 
    else 
    puts "Wrong request. Enter Y or N" 
    end 
end 

這裏LOPP將運行到斷點沒有得到執行

您可以修改1第二件事是合適的在你的代碼中是

sprint = gets.chomp 

這會提取最後一個特殊的c你的字符串的字符是由獲得和工作正常在你的情況下