ruby使用if-inside循环和用户输入
我试图使循环通过if语句,若用户输入无效,它会一直告诉输入数字,若为真,则中断 我试过了这是我的密码ruby使用if-inside循环和用户输入,ruby,loops,if-statement,user-input,Ruby,Loops,If Statement,User Input,我试图使循环通过if语句,若用户输入无效,它会一直告诉输入数字,若为真,则中断 我试过了这是我的密码 class String def numeric? Float(self) != nil rescue false end end cond = false puts "Enter number " line = gets.chomp.strip while cond == false if (line.numeric? ) puts "Ok ni
class String
def numeric?
Float(self) != nil rescue false
end
end
cond = false
puts "Enter number "
line = gets.chomp.strip
while cond == false
if (line.numeric? )
puts "Ok nice "
cond = true
else
puts "Please enter number only "
end
end
但如果条件为假,只需打印“请仅输入数字”即可继续循环
我很乐意接受任何建议
谢谢试试这个:
while cond == false
if (line.numeric? )
puts "Ok nice "
cond = true
else
puts "Please enter number only "
line = gets.chomp.strip
end
end
while true
print "Enter number "
line = gets.chomp.strip
if line.numeric?
puts "Ok nice"
break
else
puts "Please enter number only"
end
end
问题是,在告诉用户只需输入一个数字后,您不会读取另一个数字,您只需返回 解决此问题的最简单方法是将提示符和输入移动到
while
循环中,有点像这样:
class String
def numeric?
Float(self) != nil rescue false
end
end
cond = false
while cond == false
puts "Enter number "
line = gets.chomp.strip
if (line.numeric? )
puts "Ok nice "
cond = true
else
puts "Please enter number only "
end
end
在重写String方法之后,请立即尝试以下操作:
while true
print "Enter number "
line = gets.chomp.strip
if line.numeric?
puts "Ok nice"
break
else
puts "Please enter number only"
end
end
你不需要再打电话了。