----------------------------
number = 5 + rand(65)
puts "Try to guess the Magic NuMbeR is between 5 and 69"
begin
user_try = gets.chomp.to_i
puts "The NuMbeR is #{user_try > number ? 'smaller' : 'bigger'} than
#{user_try}! Try again:" unless user_try == number
end until user_try == number
puts "Congratulations! You found the Magic NuMbeR! The NuMbeR is #
{number}."
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.
----------------------------
number = 5 + rand(65)
puts "Try to guess the Magic NuMbeR is between 5 and 69"
begin
user_try = gets.chomp.to_i
puts "The NuMbeR is #{user_try > number ? 'smaller' : 'bigger'} than
#{user_try}! Try again:" unless user_try == number
end until user_try == number
puts "Congratulations! You found the Magic NuMbeR! The NuMbeR is #
{number}."
Just for fun, here's a little rewrite:
number = 5 + rand(65)
print "Try to guess the Magic NuMbeR between 5 and 69: "
diff = { false => "bigger", true => "smaller" }
loop do
user_try = gets.to_i
break if user_try == number
puts "The NuMbeR is #{diff[user_try > number]} than #{user_try}!"
print "Try again: "
end
puts "Congratulations! You found the Magic NuMbeR!" puts "The NuMbeR is #{number}."
David
···
On Sat, 10 Oct 2009, Miguel Regedor wrote:
--
The Ruby training with D. Black, G. Brown, J.McAnally
Compleat Jan 22-23, 2010, Tampa, FL
Rubyist http://www.thecompleatrubyist.com