I've got this method I wrote to ask n-times for user input using a while loop inside. The idea is really simple and common, repeat the while loop if the condition is true, The problem is that it doesn't work...
def play_again?
flag = true
while flag
print "Would you like to play again? [y/n]: "
response = gets.chomp
case response
when 'y'
Game.play
when 'n'
flag = false
end
end
flag
end
play_again?
As it stands it will only successfully repeat once and then exit, instead of keep on looping, Could you guys please tell me what is wrong? (Sorry if it's such a n00b question, I'm a ruby n00b after all)
Thank you.
Possible problems:
You may also use regular expressions (example N) or with a list of answers (yes) to check the answer:
def play_again?
while true
print "Would you like to play again? [y/n]: "
case gets.strip
when 'Y', 'y', 'j', 'J', 'yes' #j for Germans (Ja)
puts 'I play' # Game.play
when /\A[nN]o?\Z/ #n or no
break
end
end
end
play_again?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With