2013-08-16 77 views
1

我正在第一次學習ruby和計算機科學主題。我正在閱讀克里斯派恩的「學習編程」一書,並對一個例子有疑問。爲什麼在這個While Loop例子中的答案變量?

下面是代碼:

def ask(question)       # new method with paramater question 
    while true        # starts a loop 
    puts question       # puts the question on the screen 
    reply = gets.chomp.downcase    # gets the question and makes it lower case 

    if (reply == "yes" || reply == "no") # if reply was yes or no 
     if reply == "yes"      # nested if statement if yes answer == true 
     answer = true      # WHAT?? 
     else         # the else of the second if 
     answer = false      # WHAT?? why do we care about answer?? 
     end 
     break         # Breaks the Loop 
    else         # the else of the 1st if 
     puts ' Please answer "yes" or "no".' 
    end 
    end 
    answer         # Why is answer here? 
end 

我的問題是,爲什麼我們需要的 「答案」?我不明白它對環路有什麼影響。 while循環設置爲true而不是回答。

回答

1
end 
answer          #Why is answer here? 
end 

它是有從方法ask返回的answer(無論是truefalse)的結果。

我的問題是爲什麼我們需要「回答」?

answer需要根據您的示例來保存將在方法執行完成時返回的布爾值。您的while循環是無限循環,當reply將具有'yes''no' vlaue時,該循環只能被break聲明破壞。

+0

謝謝!我明白這一點,但爲什麼我們甚至真的關心這個呢?它不會影響我們的循環嗎?還是真的什麼?如果答案是肯定的,我們可以只有答案= 5,如果答案是否定答案= 4? – HelloWorld

+0

我有點看到它。你怎麼沒有在循環之外預定義answer = true,然後設置while回答(現在是真的)?那麼循環中的休息又是什麼?我認爲這就是打破循環? – HelloWorld

+0

@Babai,雖然接受,你的答案是不正確的。 '回答'不需要退出無限while循環。這也可以通過直接返回「true」或「false」來實現,從而消除了「answer」變量。 – Max

4

Ruby返回它執行的最後一條語句。實際上,它與書寫相同

return answer; 

...以類似於C或Java的語言。

+0

這就是下一個練習是用回報替換答案。我只是想抓住答案的重要性?我真的不知道它是如何連接或影響我的循環中的任何東西?打破我的while循環回答?或者是「突破」打破我的循環? – HelloWorld

+1

@Codey:將'answer'放在方法的末尾與你的循環無關。 'break'正在打破你的循環,讓你可以看到'answer'語句 - 我重新格式化了你的問題中的代碼,以便直觀地強調這一點。 Ruby的默認行爲是返回在方法中評估的最後一個表達式的值,因此您不需要顯示許多其他語言中顯式的'return ...'語句。當最後一個表達式是'answer'時,'answer'的當前值就成爲'ask(question)'方法的返回值。 – pjs

相關問題