Just started working through the Ruby chapter in Mr. Tate's "Seven Language in Seven Weeks".
For the bonus question in Day 1, I am to generate a "random" number, read a user's guess from the input, and compare the guess to my "random" number, then prompt the user to continue guessing with the begin
loop. However, the loop seems to terminate regardless of what the value of the string the user inputs.
# file : day1_bonus.rb
# Seven Languages In Seven Weeks
#
# Guess a random number!
again = "y"
begin
print "Enter a number between 0 and 9: "
number = gets.to_i
randNum = rand(10)
if number == randNum
puts 'You guessed correctly!'
else
puts 'You guessed incorrectly.'
end
print "Play again? (y/n): "
again = gets
again.chomp # remove carriage return
end while again == "y"
Output:
Enter a number between 0 and 9: 3
You guessed incorrectly.
Play again? (y/n): y
nil
There are two versions of chomp
. The regular chomp
and bang chomp!
. The difference being: regular returns modified string (and leaves source alone) while the bang version modifies original string in-place.
So, in your code you chomp the carriage return and throw away this work. Either do this
again = again.chomp
or this
again.chomp!