只接受数字输入 [英] Accept only numeric input
问题描述
我想强制用户只从控制台输入数值.下面是我应该这样做的代码.
I want to force user to enter only numeric value from console. Below is my piece of code that is supposed to do that.
puts "Enter numeric value: "
result = gets.chomp
if result.to_i.is_a? Numeric
puts "Valid input"
else
puts "Invalid input."
end
即使我输入字符串值,它也会打印 Valid input
.原因是每个字符串在 Ruby 中都有一些等效的数值.有人可以帮我正确修复条件,以便当用户输入非数字值时,脚本提示 Invalid input.
?
It prints Valid input
even if I enter a string value. And the reason is that every string has some equivalent numeric value in Ruby. Can someone help me fix the condition properly so that when user enters a non-numeric value, the script prompts Invalid input.
?
推荐答案
试试正则表达式,像这样:
Try regular expressions, like this:
puts "Enter numeric value: "
result = gets
if result =~ /^-?[0-9]+$/
puts "Valid input"
else
puts "Invalid input."
end
上面的例子只允许数字 [0..9].如果您不仅想读取整数,也可以允许使用点:^-?[0-9]+$/
.阅读有关 Ruby 中正则表达式的更多信息:http://ruby-doc.org/core-2.2.0/Regexp.html
The example above allows only digits [0..9].
If you want to read not only integers, you can allow a dot as well: ^-?[0-9]+$/
. Read more about regexp in Ruby: http://ruby-doc.org/core-2.2.0/Regexp.html
这篇关于只接受数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!