Hello! I am making a numbers guessing game that, when the user repeats a
number already guessed, returns “You’ve already guessed that. Guess
again!”
So far I have what is below. Any help is much appreciated!
number = rand(1…10)
num_guesses = 0
puts “I’m thinking of a number from 1 to 100. Try to guess it!”
loop do
print “What is your guess?”
guess = gets.chomp.to_i
num_guesses += 1
unless guess == number
message = if guess > number
"Your guess is too high."
else
puts “Your guess is too low.”
end
puts message
else
puts “You guessed right!”
puts “It took you #{num_guesses} tries to guess my number!”
exit
end
end
How about this:
number = rand(1…100)
puts ‘Random number between 1 and 100, try and guess what it is’
guess = gets.to_i
attempts = 1
until guess == number do
if guess < number then puts ‘Too small, try again’
elsif guess > number then puts ‘Too big, try again’
end
attempts += 1
guess = gets.to_i
end
puts “You guessed my number in #{attempts}
attempt#{‘s’ if attempts > 1}!”
Hi Marcc! Thanks for your answer. It looks great. I had one question
though - when the user guesses the same number, it needs to return
“Already guessed. Guess again!” Do you know how I would do that?
until guess == number do #until the user guesses the number
if guess = array then puts “You already guessed that. Try again!”
elsif guess < number then puts “Too low, try again!”
elsif guess > number then puts “Too high, try again!”
end
attempts += 1 #allows for other attempts
guess = gets.to_i #converts string into integer
end
end
puts “You guessed my number in #{attempts}
attempt#{‘s’ if attempts > 1}!”