C. Ball
C. Ball

Reputation: 711

How can I write a while loop that checks for a "Y" or "N" character in Ruby?

I'm trying to write a while loop forcing my user to confirm a choice by typing either "Y" or "N":

answer = ""

while (!answer.eql?("Y") || !answer.eql?("N"))

    puts "Do you wish to continue? ('Y' or 'N')"
    answer = gets.chomp.upcase

end

The condition of the while statement evaluates to true and goes into the body of the loop every time, because I start out with an empty string in my variable.

When I enter something random and invalid like "X" into the prompt in response to the question, the loop continues as it should, because the while statement should still be true.

But when I enter "Y", "y", "N" or "n" in response to the question, the loop still continues, when logically it should stop because the while condition should then be false.

Could anyone tell me what I'm doing wrong in the syntax of my while statement? Or is there something wrong with how I'm storing the user input in the variable?

Upvotes: 1

Views: 358

Answers (2)

Raman Kumar Sharma
Raman Kumar Sharma

Reputation: 413

Alternate solution:

answer = ""

until ["Y","N"].include? answer

    puts "Do you wish to continue? ('Y' or 'N')"

    answer = gets.chomp.upcase

end

Upvotes: 2

gunn
gunn

Reputation: 9165

There is an error in your logic. If answer is Y then obviously it's not equal to N, and so the condition of the loop is met.

You can fix this by using an 'and' in your condition:

(!answer.eql?("Y") && !answer.eql?("N"))

Upvotes: 3

Related Questions