Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
random number guesser
guessNumber = rand(GUESS_RANGE)
puts "Guess the number! (Hint: between 0 and #{GUESS_RANGE})"
guessCount = 0
while (userGuess = gets.to_i) != guessNumber # keep getting more numbers
# give out hints to the user
puts 'Too high' if userGuess > guessNumber
puts 'Too low' if userGuess < guessNumber
guessCount = guessCount + 1
puts "you got it in #{guessCount} guesses! The number is: #{guessNumber}"

a-leung commented Oct 25, 2012

I extended it a bit more so the range is higher (GUESS_RANGE), tracking the number of guesses it would take (guessCount), and NOT declaring the 'input' variable until the while comparison (that is something NOT good in C... maybe possible, but definitely leads to memory leaks!)

The big difference is inside the while loop, I find having the output before the test (puts ... THEN if ...) leads to a different way to read code: once you see 'Too High', you automatically know what's going to happen next: greater than comparison! (AND it doesn't matter which order I put the comparison using this style) For me, this leads to less 'decoding' of the code because the result is at the beginning, I already know what's the conclusion. These small things add up to make more readable code, which is always good style.

afeld commented Nov 13, 2012

You should initialize the guessCount to 1, and use an if/elseif since they are mutually exclusive anyway. Lastly, the Ruby convention is to use lowercase with underscores for variable names. Nice work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment