我第一次学习红宝石和计算机科学专题。我正在阅读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而不回答。
答案 0 :(得分:4)
Ruby返回它执行的最后一个语句。实际上,它与写作相同
return answer;
...用C语言或Java语言。
答案 1 :(得分:1)
end
answer #Why is answer here?
end
可以从方法answer
返回true
(false
或ask
)的结果。
根据您的示例,我的问题是为什么我们需要“回答”?
answer
需要保存布尔值,该值将在方法执行完成时返回。您的while
循环是一个无限循环,当break
将reply
或'yes'
为'no'
时,{{1}}语句只能打破{{1}}循环。< / p>