1

我是第一次学习红宝石和计算机科学主题。我正在阅读 Chris Pine 所著的“学习编程”一书,并且对一个示例有疑问。

这是代码:

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 不回答。

4

2 回答 2

4

Ruby 返回它执行的最后一条语句。实际上,它与写作相同

return answer;

...使用 C 或 Java 等语言。

于 2013-08-16T20:23:32.230 回答
0
end
 answer                                     #Why is answer here?
end

它可以从方法返回answertruefalse)的结果ask

我的问题是为什么我们需要“答案”?

answer根据您的示例,需要保存在方法执行完成时要返回的布尔值。你的while循环是一个无限循环,它只能被break语句打破,什么时候reply会有'yes''no'vlaue。

于 2013-08-16T20:23:41.133 回答