Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
guessing game (ruby)
# solution to
def main
lower_bound = 1
upper_bound = 100
puts "Think of a number between 1 and 100, inclusive."
puts "At each guess, answer with 'l' to indicate your number is lower than the guess, 'h' to indicate your number is higher than the guess, or 'y' to indicate the guess is correct."
while true
guess = (lower_bound + upper_bound) / 2
puts "Is #{guess} your number?"
input = gets
case input.strip
when "l" # the number is less than than `guess`
upper_bound = guess - 1
when "h" # the number is greater than `guess`
lower_bound = guess + 1
when "y" # `guess` is the correct number, so bail out
puts "Your number is #{guess}."
raise "You lied! You didn't pick a number between 1 and 100!" unless lower_bound <= upper_bound
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment