只接受数字输入 [英] Accept only numeric input

查看:58
本文介绍了只接受数字输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想强制用户只从控制台输入数值.下面是我应该这样做的代码.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆