1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Worked Example: Number Guessing Game


Worked Example: Number Guessing Game

What is a worked example? A worked example is a full explanation of a completed program. If the program is complex enough, the program will be showed multiple times in various states of development. If you've been reading the other articles on the site, much of the information may not be new. But if you do come across anything new, there will likely be some links to helpful articles.

When I first learned how to program, one of the first games I wrote was a simple number guessing game. On every computer that I used, I tried to re-write this program in whatever dialect of BASIC it spoke. The game is simple, the program thinks of a random number from 1 to 100, you make guesses and it tells you if you're too high or too low. This program teaches how to use the random number generator, basic input and output, loops and conditionals.

Random Numbers

Computers cannot generate truly random numbers. Some would argue people cannot generate random numbers either, everything is predetermined in some way. Computers, however, can generate pseudo-random numbers. They're "random enough" to be able to fool a person. This is done by an algorithm behind the scenes. You don't really need to know how it works, but you should know that this algorithm needs to be "seeded." Normally Ruby does this for you, so we won't worry about it here.

Random numbers are generated using the rand method. It's a method of the Kernel module, so the rand method is available everywhere. If no argument is passed, it will return a random floating point number from 0 to 1. If an integer or Range object is passed, it will generate an integer from either 0 to that number, or an integer that falls in the passed range.

So, we want a number from 1 to 100. Knowing what we know now, it should be obvious how to do this: rand(1..100).

Printing, Newlines and Input

In many programming languages (I'm looking at you, C) you have to explicitly print a newline character at the end of every line. If you don't, your output looks like a run-on sentence, and it's very difficult to read. Ruby provides the puts method that will print a string followed by a newline. But what if you don't want to print the newline? The print method is what you want. It prints a string without the newline.

Input is fairly straightforward. The gets method will let you type anything you wish into the console and read it all into a string until you press the enter key. Once you press the enter key, the program will continue on. Here, we use a common idiom that reads a line, chomps the newline from it and converts it from a string into a number. This is necessary. Say, for example, you enter the guess of "10". This is two characters, a "1" and a "0" as a string. But this is not how Ruby represents numbers, this is a character representation of a number in a string. You must call the to_i method on the string to return a number.

So put altogether, this idiom becomes gets.chomp.to_i. In other words, wait for the player to type their guess and hit enter, take the newline character off and convert this input to a number.

Looping and Conditionals

At the heart of this little game is a loop. A loop will execute the statements inside the loop from beginning to end. If the loop determines it should go again (loops usually have a conditional, like "loop while a is greater than 10"), it starts at the beginning of the loop and so on. It can even do that forever, or until you end the program some other way.

This program uses the loop do loop. This is an infinite loop. It will go on forever, until an exception is raised or a break statement is encountered. If your program ever gets stuck in an infinite loop with no way to get out, pressed ctrl c to end the program or close the terminal window.

The last thing to talk about is the conditional statement. If you've guessed the correct number, or if you're too high or too low, the conditional statement is how the program knows what to do. If you're too high, say you're too high and loop again. If the guess is correct, congratulate the player and break out of the loop.

The Program

Put this all together and you get the following program. At the top you'll see the random number being generated. The main loop stands out pretty easily. One thing you'll notice is that the message variable gets assigned the output of a conditional. Conditionals are like methods, they evaluate to the last statement executed in them. And finally the congratulation and an exit method call, which ends the program.

#!/usr/bin/env ruby

number = rand(1..100)
num_guesses = 0

puts "I'm thinking of a random number from 1 to 100"
puts "Can you guess it?"

loop do
  print "What is your guess? "
  guess = gets.chomp.to_i
  num_guesses += 1

  unless guess == number
    message = if guess > number
                "Too high"
                "Too low"
    puts message
    puts "You got it!"
    puts "It took you #{num_guesses} guesses."
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Worked Example: Number Guessing Game

©2014 About.com. All rights reserved.