Skip to content

Instantly share code, notes, and snippets.

@a-leung
Created October 24, 2012 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-leung/3946690 to your computer and use it in GitHub Desktop.
Save a-leung/3946690 to your computer and use it in GitHub Desktop.
random number guesser
GUESS_RANGE = 100
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
end
puts "you got it in #{guessCount} guesses! The number is: #{guessNumber}"
@a-leung
Copy link
Author

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
Copy link

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