2016-10-29 163 views
-4

當我運行下面的代碼時,仍然收到未定義的本地變量錯誤。這個問題似乎源於我的gets.chomp。 我已經包含整個程序,以便有一點上下文。這個問題似乎來自第16行,但即使我刪除第一個gets.chomp,我也會得到同樣的錯誤。未定義的本地變量錯誤

def test() 
    score = 0 
    def scorekeeper(input, answer) 
    if input == answer 
     puts "Correct!" 
     score += 10 
     puts score 
    else 
     puts "incorrect :(" 
    end 
    end 

    puts "Welcome to Virtual Math Test V1.0.0" 
    sleep 0.7 
    puts "What is Your Name?" 
    gets.chomp = username 

    puts "Question 1) \n 24 * 24" 
    gets.chomp = ans1 
    scorekeeper(ans1, 24 * 24) 
    system "clear" 

    puts "Question 2) \n 28/4" 
    gets.chomp = ans2 
    scorekeeper(ans2, 28/4) 
    system "clear" 

    puts "Question 3) \n 754 + 222" 
    gets.chomp = ans3 
    scorekeeper(ans3, 976) 
    system "clear" 

    puts "Well Done!" 
    puts "#{username} scored #{score} points out of 30!" 
    sleep 0.4 
    puts "do you want to take the test again? y/n" 
    gets.chomp.downcase = repeatyn 

    if repeatyn == y || yes 
     test() 
    else 
     abort("Ok, See you later #{username}!") 
    end 
end 

test() 

謝謝!

+1

它是'username = gets.chomp'而不是'gets.chomp = username' –

+0

命令很重要:'gets.chomp = username'意思是'設置'gets.chomp'到'username'的值(它不會'存在)'。試試'username = gets.chomp'(等其他例子)。 – Aurora0001

+1

當您報告錯誤信息時,請提供完整的信息(除了相關的回溯信號外)和其發生的行(您提供的信息)。您省略的信息是未定義的局部變量或方法,它包含在消息中:「用戶名」,這或多或少指出了問題。如果違規消息的右側是「cat」,那麼錯誤消息應該是'NoMethodError:undefined method'chomp ='for「cat \ n」:String',因爲'chomp ='被Ruby讀取爲'chomp ='方法沒有定義。錯誤消息值得尊重! –

回答

1

你的任務是南轅北轍,下面

gets.chomp = username 
gets.chomp = ans1 
gets.chomp = ans2 
gets.chomp = ans3 
gets.chomp.downcase = repeatyn 

應該寫成:

username = gets.chomp 
ans1 = gets.chomp 
ans2 = gets.chomp 
ans3 = gets.chomp 
repeatyn = gets.chomp.downcase 

分別。

+0

謝謝,夥計。這是我腦中的一個死腦筋。 –