在一个简单的循环中重新尝试逻辑

时间:2016-05-24 23:50:49

标签: ruby

我正在尝试为数组设置边界,稍后将在控制台中打印并求和。下限($ a)应该小于50并且我编写了这段代码来评估它,但是如果输入更高的数字,我希望它重新提示输入一个数字。到目前为止,谷歌和实验都让我失望。

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
    end
end

1 个答案:

答案 0 :(得分:0)

您可以重新构建循环,以便提示和调用gets都在其中:

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
  end

  # return the entered value to the caller
  a
end

此外,正如我在示例中所示,我建议避免使用全局变量(在这种情况下为$a)。