I started with:
puts "Hello there, and what's your favorite number?"
favnum = gets.to_i
puts "Your favorite number is #{favnum}?" " A better favorite number is #{favnum + 1}!"
puts "Now, what's your favorite number greater than 10?"
favnumOverTen = gets.to_i
if favnumOverTen < 10
puts "Hey! I said GREATER than 10! Try again buddy."
else
puts "Your favorite number great than 10 is #{favnumOverTen}?"
puts "A bigger and better number over 10 is #{favnumOverTen * 10}!"
puts "It's literally 10 times better!"
end
That worked fine, but if the user entered a number less than 10 the program ended. I want the user to be prompted to try again until they enter a number greater than 10. Am I supposed to do that with a loop?
Here's what I took a swing at, but clearly it's wrong:
puts "Hello there, and what's your favorite number?"
favnum = gets.to_i
puts "Your favorite number is #{favnum}?" " A better favorite number is #{favnum + 1}!"
puts "Now, what's your favorite number greater than 10?"
favnumOverTen = gets.to_i
if favnumOverTen < 10
loop.do
puts "Hey! I said GREATER than 10! Try again buddy."
favnumOverTen = gets.to_i
until favnumOverTen > 10
else
puts "Your favorite number great than 10 is #{favnumOverTen}?"
puts "A bigger and better number over 10 is #{favnumOverTen * 10}!"
puts "It's literally 10 times better!"
end
A better solution would be to get the favorite number of 10 once, then start an until
loop checking for favnumOverTen > 10
like this:
puts "What is your favorite number greater than 10?"
favnumOverTen = gets.to_i
until favnumOverTen > 10 do
puts "Hey! I said GREATER than 10! Try again buddy."
favnumOverTen = gets.to_i
end
This way, if the initial entry is greater than 10, the until loop is never executed (saves you the if
statement).
Also, just so you're aware, it's not considered idiomatic Ruby to write variable names using camel case (i.e. favnumOverTen
should be favnum_over_ten
).
Here's a way that's a little shorter than the previous two:
puts "Now, what's your favorite number greater than 10?"
until (favnumOverTen = gets.to_i) > 10
puts "Hey! I said GREATER than 10! try again buddy."
end
This works because assignment returns the value assigned to the variable.
while line = gets ...
example many a tim - Jwosty 2012-04-04 00:26