gpt4 book ai didi

ruby - 如果变量被声明为 false,程序如何前进?

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:51 27 4
gpt4 key购买 nike

程序如何在“bear_moved = false”之后继续?如果 while 语句只运行 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

最佳答案

在我看来,您想要如下内容:

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 .我以不同的方式编写它只是为了向您展示可用的选择。

  • 你不需要 when "taunt bear" 下的 if bear_moved...else...end,因为 bear_moved 在该点始终为 false

  • 没有方法或局部变量 deadgold_room,因此您需要对此做些事情。我已经为它们添加了方法。

  • 我使用了 case 语句而不是所有的 if-elsif 语句,因为它更易于阅读。此外,您会发现在使用 case 语句时不需要变量 choice。我还只包含了 choice 的结果,在 if-then-else 中为两个 case 结果留下了次要选择.

(我最初有 while bear_moved == false。我在阅读@SteveTurczyn 的回答后将其更改为 until bear_moved。谢谢,Steve。)

关于ruby - 如果变量被声明为 false,程序如何前进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com