Reputation: 6549
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?
Upvotes: 0
Views: 708
Reputation: 8422
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.
Upvotes: 1
Reputation: 37419
number
is a number, choice
is a string. You need to parse the string for this to work:
choice = gets.chomp.to_i
Upvotes: 3