Guessing Game

excerpt: This covers the basic building blocks such as Reading User Input, while Loop and Counter. tags: read-user-input while-loop counter

Write a guessing game where you have to guess a secret number between 1 and 100. After every guess the program tells the user whether the number was large or small. At the end, print the number of tries needed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def guess
  secret_number = 9
  guess = ""
  guess_count = 0

  while guess.to_i != secret_number
    puts "Enter guess: "
    guess = gets.chomp
    guess_count += 1
    
    if guess.to_i < secret_number
      p "Number is greater than #{guess}"
    elsif guess.to_i > secret_number
      p "Number is less than #{guess}"
    end
  end
  
  guess_count
end

p "Number of tries: #{guess}"

Replace the hard coded secret number with generating a random number between 1 and 100 (inclusive of 1 and 100):

1
secret_number = rand(1..100)

Building Blocks

  • Reading User Input
  • while Loop
  • Counter