仅接受数字输入

时间:2015-08-21 18:20:49

标签: ruby

我想强制用户只从控制台输入数值。下面是我应该做的那段代码。

echo $this->Form->input('tags.0.id', [
    'type' => 'select',
    'multiple' => false,
    'options' => $tagList,
]);

即使输入字符串值,它也会打印puts "Enter numeric value: " result = gets.chomp if result.to_i.is_a? Numeric puts "Valid input" else puts "Invalid input." end 。原因是每个字符串在Ruby中都有一些等价的数值。有人可以帮我正确修复条件,以便当用户输入非数字值时,脚本会提示Valid input吗?

3 个答案:

答案 0 :(得分:6)

to_i会将任何字符串转换为整数,即使它不应该:

package Project_Folder;

import java.util.Scanner;

public class Testing2 {

    private static Scanner input;

     public static void main(String[] args) {
        input = new Scanner(System.in);
        String mood;
        String f;

        System.out.println("Describe how you are feeling?");
        mood = input.next();
        if (mood has sad inside){
            System.out.println("I hope you will feel better later");
        } else if (mood has wierd inside){
            System.out.println("I hope you will feel better later");
        } else if (mood has happy inside){
            System.out.println("cool you are lucky I cannot feel emmotions"); 
        }
    }
}

返回find /var/lib/elasticsearch/elasticsearch/nodes/ -name "*.recovering"

您想要做的是:

"asdf".to_i
如果字符串无法转换为整数,

0会抛出异常,而puts "Enter numeric value: " result = gets.chomp begin result = Integer(result) puts "Valid input" rescue ArgumentError, TypeError puts "Invalid input." # handle error, maybe call `exit`? end 在这些情况下会给出0,这就是Integer(some_nonnumeric_string)始终为真的原因。

答案 1 :(得分:0)

尝试正则表达式,如下所示:

puts "Enter numeric value: "
result = gets

if result =~ /^-?[0-9]+$/
    puts "Valid input"
else
    puts "Invalid input."
end

以上示例仅允许数字[0..9]。 如果您不仅要读取整数,还可以允许使用点:^-?[0-9]+$/。阅读有关Ruby中regexp的更多信息:http://ruby-doc.org/core-2.2.0/Regexp.html

答案 2 :(得分:0)

如果你的意思是整数"数字",那么:

puts "Enter numeric value: "
result = gets.chomp
case result
when /\D/, ""
  puts "Invalid input"
else
  puts "Valid input."
end

它还会处理空字符串,这些字符串会被0转换为to_i,这可能是您不想要的。