2014-03-27 40 views
0

我有這個因子應用程序,應該是無限的,如果答案總是"y"紅寶石:函數/方法位置

def continue? 
    answer = gets 
    if answer.downcase == "y" 
    main 
    elsif answer.downcase == "n" 
    exit 
    else 
    "This means n to me. Follow the rules next time. Bye." 
    end 
end 

def main 
    p "Enter any Integer" 

    out = gets 

    num = out.to_i 
    def factorial(num) 
    sum = num 
    (num-1).times {sum = sum * (num - 1); num = num-1} 
    sum 
    end 

    p factorial(num) 
    p "Do you want another number" 
    continue? 
end 

main 

起初,#繼續嗎?是在應用程序的結尾,但是當我在#main中調用繼續時,我會爲不存在的Method發生錯誤。所以,我感動了#繼續?到頂端,但現在我不能再次調用#main,因爲同樣的方法錯誤。我可以把#繼續?在#main方法裏面,但我不認爲它會做很多。處理這種情況有沒有更好的方法?

如果我的代碼關閉或者我的練習不是最好的,請讓我知道。我會使用#inject進行階乘,但是我正在使用ruby 1.8.5,所以我必須盡我所能。

回答

3

首先,從另一個函數調用main是很奇怪的,因爲main在程序啓動時只能調用一次。

其次,如果你這樣做這樣你會耗盡內存,因爲你調用堆棧是要保持增長(主,繼續,繼續爲主,...)

你爲什麼不繼續?返回真實或錯誤的值。然後在主要你可以寫

begin 
    p "Enter any Integer" 

    out = gets 

    num = out.to_i 
    def factorial(num) 
     sum = num 
     (num-1).times {sum = sum * (num - 1); num = num-1} 
     sum 
    end 

    p factorial(num) 
    p "Do you want another number" 
    end while continue? 
+0

是的。這更有意義。謝謝你爲我清理東西。我從來沒有真正想過它記憶的方式,因爲它只是一小段片段。 – FiberBro

+0

很好的答案,但我會質疑你的'begin ... end'塊。爲什麼不只是「繼續? ...結束? –

+0

@ZachKemp那麼,假設代碼應該至少執行一次,之後用戶可以決定再次運行它是公平的。在這種情況下,「開始......結束而繼續?」比「持續」更有意義? ...結束。在這種情況下,在開始之前要求繼續下去會很奇怪。 –

0

你有幾個問題。首先,當你做answer = gets時,你所得到的不僅僅是一封信,它是一個字母后跟一個換行符,例如, 'y\n'。解決方案是使用str#chomp。另外,如果輸入「y」或「n」以外的字母,則實際上並未顯示任何內容。這裏是固定的方法:

def continue? 
    answer = gets.chomp 
    if answer.downcase == "y" 
    main 
    elsif answer.downcase == "n" 
    exit 
    else 
    puts "This means n to me. Follow the rules next time. Bye." 
    end 
end 
1

你可以把條件放在while循環中而不是每次調用函數。另外,請注意gets方法,你應該輸入strip

def continue? 
    answer = gets.strip 
    if answer.downcase == "y" 
    true 
    elsif answer.downcase == "n" 
    false 
    else 
    p "This means n to me. Follow the rules next time. Bye." 
    false 
    end 
end 

def main 
    begin 
    p "Enter any Integer" 

    out = gets 

    num = out.to_i 
    def factorial(num) 
     sum = num 
     (num-1).times {sum = sum * (num - 1); num = num-1} 
     sum 
    end 

    p factorial(num) 
    p "Do you want another number" 
    end while continue? 
end 

main