程序如何在''bear_moved = false'‘之后继续运行?如果while语句仅在true时运行,程序如何继续运行?或者while true与'bear_moved‘无关?如果是这样,那它又有什么关系呢?
def bear_room
puts "There is a bear here."
puts "The bear has a bunch of honey."
puts "The fat bear is in front of another door."
puts "How are you going to move the bear?"
bear_moved = false
while true
print "> "
choice = $stdin.gets.chomp
if choice == "take honey"
dead("The bear looks at you then slaps your face off.")
elsif choice == "taunt bear" && !bear_moved
puts "The bear has moved from the door. You can go through it now."
bear_moved = true
elsif choice == "taunt bear" && bear_moved
dead("The bear gets annoyed and chews your leg off.")
elsif choice == "open door" && bear_moved
gold_room
else
puts "I got no idea what that means."
end
end
end发布于 2014-09-02 05:00:07
在我看来,您需要的内容如下所示:
def bear_room
puts "There is a bear here."
puts "The bear has a bunch of honey."
puts "The fat bear is in front of another door."
puts "How are you going to move the bear?"
bear_moved = false
until bear_moved
print "> "
case gets.chomp
when "take honey"
dead("The bear looks at you then slaps your face off.")
when "taunt bear"
puts "The bear has moved from the door. You can go through it now."
bear_moved = true
when "open door"
gold_room
else
puts "I have no idea what that means."
end
end
puts "I'm outta' here!"
end
def dead(str) puts(str) end
def gold_room; puts "So this is the famous gold room. Nice."; end需要考虑的几点:
while true,因此需要一条break语句来退出循环。或者,您可以使用until bear_moved,就像我所做的那样。如果您想使用while true (或者更常用的loop do),只需将until bear_moved替换为break。我用不同的方式写了它,只是为了向你展示available.when "taunt bear"下不需要if bear_moved...else...end的选择,因为bear_moved在这一点上总是false。dead或gold_room,所以你需要对此做点什么。我已经为这些添加了方法。case语句,而不是所有的if-elsif语句,因为它更容易阅读。此外,您可以看到,在使用case语句时,您不需要变量choice。我还只包含了choice的结果,在if-then-else中留下了两个case结果的次要选择。<代码>H229<代码>F230(我最初使用的是while bear_moved == false。在阅读了@SteveTurczyn的答案后,我将其更改为until bear_moved。谢谢,史蒂夫。)
发布于 2014-09-02 05:00:47
while true是另一种说法
while true == true当然,这是永远正确的。您只能通过显式的break命令走出while true循环。
你想做的(我认为)是……
until bear_moved这意味着您将继续循环,直到执行完bear_moved == true
发布于 2014-09-02 06:05:45
我认为你没有掌握“状态”的概念,也就是事物所处的状态。最初,熊(根据文本,隐含地)在门前。熊的状态是“未从其初始位置移动”,并由布尔变量bear_moved捕获,该变量设置为值false。while true将继续无限地重复所包含的逻辑,直到您发出导致熊移动或熊杀死您的命令为止。看起来正确的动作顺序是嘲弄熊-如果它没有移动,正如bear_moved状态变量所指示的那样,它将移动,但如果它已经移动了,并且您再次嘲笑它,熊将会生气并咬掉您的腿。
基本上,遵循的逻辑链取决于状态,即在这种情况下,熊的状态(移动或未移动)与您的操作选择之间的交互。
https://stackoverflow.com/questions/25612598
复制相似问题