Solution: Number guessing game in Ruby


In thisexercise, you were asked to create the first version of theNumber guessing game.


hidden = rand(200)# puts hiddenprint "Type in your guess: "guess = gets.to_iif guess == hidden puts "Hit"elsif guess < hidden puts "Your guess is smaller that the hidden number"else puts "Your guess is bigger that the hidden number"end

We use the randfunction to generate a random number. If we called it without any parameter, randwould return a floating point number between 0 and 1. As we passed a whole number to it, the randfunction generated a whole number between 0 and 200, the number we gave.

There is a commented out line printing the hidden value back. I used it to be able to test the code which was comparing my input to the hidden number.

Then we use the printfunction to ask the user to type in a number. We use the printfunctions instead of the putsfunction to avoid adding a trailing newline. So the cursor will appear on the same line where the request was printed.

getsreads in whatever we type in response. to_iconverts it to integer. (By default when we read in something from the standard input, that will be a string. Even if it only contains numbers. We have to tell Ruby to convert it to an integer.)

Then we have 3 cases depending the relative values of the hiddenand guessvariables.