John K. wrote:
I’m trying to figure out how to get a user to be able to submit guesses
in a guessing game multiple times.
Hi John. There are bunches of ways you could do this, but here is what
I’d do.
#################### CODE
###############################################
puts “I’ve picked a number between 1 and 10. See if you can guess it!”
until 4 == gets.chomp.to_i
puts “WRONG! Try again.”
end
puts “You got it!”
################## END CODE
#############################################
UNTIL is like a while loop but it loops ‘until’ a condition is met. In
other words, WHILE will loop as long as a condition is TRUE, and UNTIL
will loop until a condition is FALSE.
You could also write the until line as:
while 4 != gets.chomp.to_i
and it would be the same thing.
I noticed that I didn’t use a single variable in that code. If you
wanted,
you could have used a variable in place of the constant fixnum 4, and
just assigned a value to it.
As far as your code goes … your if/ifelse statements, while
functional, are
not very pretty. Since all you are doing is looking for the CORRECT
answer, you could have written …
if secret_number == guessed_number
print “You guessed it!\n”
else # this covers all other cases.
print “Nope! Guess again.\n”
end
And that would be simpler. ifelse in general is an ugly construct in my
opinion and so I tend to choose CASE when I need to evaluate multiple
conditions.
Hope this helps!