public
Created

random number guesser

  • Download Gist
random-v2.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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}"

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.

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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.