0

I'm attempting to make a random number guessing game in Ruby. I'm rather new so perhaps the answer is obvious but why won't this work?

number = rand(5)
choice = 9999
while number != choice do
    puts "Guess the number #{number}"
    choice = gets.chomp
end
puts "You guessed Correctly! #{number} was the correct number."

As you can see I limited it to numbers between 0 and 4. Then the while loop runs while the guess made by the user is different from the random number generated. However, even when the user enters the correct number, the while loop continues looping. As you can see I've even printed the generated number so I know which to guess.

Any idea what's going wrong here?

2 Answers 2

3

number is a number, choice is a string. You need to parse the string for this to work:

choice = gets.chomp.to_i
Sign up to request clarification or add additional context in comments.

1 Comment

This answer, combined with the knowledge that chomp does not need to precede to_i method.
1

You probably should be using something else to be comparing the number returned from the rand() function and the string returned from gets.

Perhaps the spaceship operator (<=>) would work, combined with turning the number into a string using to_s, in which case the while loop header would look like

while !(number.to_s <=> choice) do

or something like that.

You don't have to use the spaceship operator, though.

1 Comment

Didn't know that gets returned a string. That was my problem. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.