Ruby 如果变量被声明为false,程序如何前进?
程序如何在“bear_moved=false”之后继续?如果while语句仅在true时运行,程序如何继续运行?或者,while true与“bear_moved”无关?如果是这样,又有什么关系Ruby 如果变量被声明为false,程序如何前进?,ruby,variables,boolean,Ruby,Variables,Boolean,程序如何在“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
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
在我看来,您需要以下内容:
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
,就像我所做的那样。如果您想使用直到bear_移动
(或者更惯用的while true
),只需将loop do
替换为
。我写的不同只是为了向你展示可用的选择直到bear\u移动
- “嘲弄熊”时,如果移动了熊,则不需要
,否则…在
下结束
,因为
时总是移动了熊
为false
- 没有方法或局部变量
或dead
,因此您需要对此采取一些措施。我已经为这些添加了方法gold\u room
- 我使用了一个
语句,而不是所有case
,因为它更容易阅读。另外,在使用if-elsif
语句时,您不需要变量case
。我还只包含了选项
的结果,将次要选择保留在选择
中,用于两个if-then-else
结果案例
。我将其改为,直到bear_在阅读@SteveTurczyn的答案后移动了。谢谢,Steve。)
这是另一种说法
while true == true
当然,这是永远正确的。您只能通过显式的break
命令退出while true
循环
你想做的(我想)是
这意味着您将继续循环,直到您执行了bear\u moved==true
我认为您没有理解“状态”的概念,即事物所处的状态。最初,熊(根据文本,隐式地)在门前。熊的状态为“从其初始位置未移动”,由布尔变量bear_moved
捕获,该变量设置为值false
。while true
将继续无限期地重复包含的逻辑,直到您发出命令,导致熊移动或熊杀死您。看起来正确的动作顺序是嘲弄熊-如果它没有移动,如bear\u moved
状态变量所示,它会移动,但如果它已经移动,你再次嘲弄它,熊会生气,并咬掉你的腿
基本上,遵循的逻辑链取决于状态,即在本例中,熊的状态(移动或不移动)与您的操作选择之间的交互。true
是一个布尔值,表示布尔值true
。while
运行时true
是真实的,这总是真实的。不客气,Cary.)对程序的良好分析。
while true == true
until bear_moved