基本Ruby编程
我有以下ruby代码,从一本学习到编程的书。我理解它,但它要求我尝试删除变量good_answer和answer。它说我必须使用return退出循环。我不知道从哪里开始。任何线索都很好,我只是想弄清楚基本Ruby编程,ruby,while-loop,function,Ruby,While Loop,Function,我有以下ruby代码,从一本学习到编程的书。我理解它,但它要求我尝试删除变量good_answer和answer。它说我必须使用return退出循环。我不知道从哪里开始。任何线索都很好,我只是想弄清楚 def ask question good_answer = false while (not good_answer) puts question reply = gets.chomp.downcase if (reply == 'yes' or reply =
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 #while ends here
answer #This is what we return (true of false)
end
puts
ask('Do you like eating Cheese?')
ask('Are you crazy?')
rain = ask 'Do you like rain?'
puts rain
我会照它说的做-把
返回
放在使用应答
的地方:
def ask question
while (true)
puts question
reply = gets.chomp.downcase
if (reply == 'yes' or reply == 'no')
if reply == 'yes'
return true
else
return false
end
else
puts 'Please answer "yes" or "no".'
end
end #while ends here
end
当你从书本上自学时,你为什么要作弊?最好是在你理解练习的内容之前,重新阅读练习的章节。我不知道为什么会有这么多人投反对票。此外,我不认为OP是在试图“欺骗”——他只是要求在正确的方向上推动。我以前读过一些好的和糟糕的教科书。我不是想作弊,这是一个我一直坚持的可选练习,我想我会看到我错过了什么。我可以跳过它,但我更愿意学习如何解决这个问题。