如何干净地验证用户输入是否是Ruby中的整数?

Pri*_*kaK 12 ruby validation integer

我有一段代码,我要求用户输入一个数字作为我的问题的答案.我可以做,to_i但棘手/垃圾输入将逃脱to_i.例如,如果用户输入693iirum5答案,则#to_i会将其删除693.

请建议一个函数,而不是正则表达式.在此先感谢您的回复.

saw*_*awa 17

这将验证输入:

Integer(gets) rescue nil
Run Code Online (Sandbox Code Playgroud)

  • 我们如何使用这段代码呢? (8认同)

Ras*_*mus 7

在回答camdixon的问题时,我提交了这个提议的解决方案.

使用接受的答案,但不要rescue nil使用rescue false简单的if来包装你的代码.

print "Integer please: " 
user_num=Integer(gets) rescue false 
if user_num 
    # code 
end
Run Code Online (Sandbox Code Playgroud)