我想用下面的代码重写下面的代码,但是我卡住了。
def ask question
good_answer = false
while (not good_answer)
puts question
reply = gets.chomp.downcase
if (reply == 'yes' or reply =='no')
good_answer = true
if reply == 'yes'
answer = true
else
answer = false
end
else
puts 'Please answer "yes" or "no"'
end
end
answer
end
替换代码:
def ask question
puts question
reply = gets.chomp
if (reply == 'yes' or reply == 'no')
puts reply.capitalize
else
puts 'Please enter "yes" or "no"'
#jump the code to like 2 ( but how?)- use while reply != empty & comment the below lines
puts question
reply = gets.chomp
end
end
我想跳转到程序的主要部分,有没有goto、jump或者我可以在那个方法里面调用方法吗?
最佳答案
I want to jump to the main part of program is there any goto, jump or can I call method inside that method?
是的,它被称为循环,即您在原始代码中使用的内容。到底为什么要用 goto 替换循环?没有意义。
然而,它可以被简化。我不喜欢检查"is"或“否”,但我也没有时间重组您的程序。
def ask question
while true
puts(question)
reply = gets.chomp.downcase
if reply == 'yes' || reply == 'no'
return reply == 'yes'
else
puts('Please answer "yes" or "no"')
end
end
end
关于ruby程序基本设计讲解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733638/