jedgil jedgil - 2 years ago 141
Ruby Question

re-try logic in a simple loop

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

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download