jedgil jedgil - 1 year ago 45
Ruby Question

learning ruby, trying to include re-try logic in a simple loop

I'm about 3 weeks into studying ruby in my spare time, so please be gentle. :)

I'm learning by writing a small number "game" and I'm trying to set bounds for an array that will later be printed in the console and summed. The lower bound ($a) should be less than 50 and I wrote this code to evaluate for that, but I want it to re-prompt for a number if a higher number is typed. So far, Google and experimentation have failed me.

def num_a
print "Pick a number from 1 to 50: "
$a = Integer(gets.chomp)
until $a < 50
puts "Um, try again please."
# need something here to prompt for another response
# until $a is less than 50

Thanks in advance for any help you can give!

Answer Source

You could restructure the loop so that the prompt and call to gets are both inside it:

def num_a
  # start with a number that doesn't meet the condition
  a = 50

  # check if the number meets the condition yet
  until a < 50
    # ask the user to enter a number
    print "Pick a number from 1 to 50: "
    a = Integer(gets.chomp)
    # ask to try again if the number isn't under 50
    puts "Um, try again please." unless a < 50

  # return the entered value to the caller

Also, as I've shown in the example, I would recommend avoiding the use of global variables ($a in this case).