Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 512
jlstr Avatar asked Dec 09 '22 05:12

jlstr


1 Answers

Possible problems:

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

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?
like image 190
knut Avatar answered Dec 21 '22 23:12

knut