首先,我想说我是红宝石的新手,我还在学习。我目前正在开展一个学校项目,其中的任务是使程序计算用户的输入。
但是,在我的程序中,我希望它只允许用户输入数字。如果用户提供任何形式的字母,它将收到错误,并让用户再次尝试,直到他给出一个数字。这样做的任何方式?
非常感谢你,如果你可以帮助我:)。
到目前为止,这是我的代码:
def calculate_one #method to calculate option 1
prompt = "> " #make it look nice
puts "What is the salary for the accountant? "
print prompt
while @accountant = gets.chomp #looping
if @accountant =~ /\A\d+\z/
puts "Error: Only use numbers. Please try again"
print prompt
else
"What is the salary for the developer? "
print prompt
while @developer = gets.chomp
if @developer =~ /\A\d+\z/
puts "Error: Only use numbers. Please try again"
print prompt
else
print "The salary for an account is #{@accountant}\nThe salary for an developer is #{@developer}"
break
end
end
end
end
end