How can I fix this Ruby Yes / No-Style loop?

I have this method that I wrote to ask n-times for user input using a while loop inside. The idea is really simple and ordinary, repeat the while loop, if the condition is true, the problem is that it does not 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? 

In its current form, it will only successfully repeat once, and then exit, and not continue the cycle. Could you please tell me what is wrong? (Sorry if this is such a question n00b, I'm actually a ruby ​​n00b)

Thanks.

+4
source share
1 answer

Possible problems:

  • check out Game.play
  • Capital / no-capital in response? → String # upcase or String # downcase
  • hidden spaces (before / after answer) -> String # strip instead of String # chomp

You can also use regular expressions (example N) or 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? 
+14
source

All Articles