Accept only numeric input

后端 未结 3 723
情深已故
情深已故 2021-01-15 06:02

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 =         


        
相关标签:
3条回答
  • 2021-01-15 06:23

    If you mean integer by "numeral", then:

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

    It also takes care of empty strings, which would be turned into 0 by to_i, which you probably do not want.

    0 讨论(0)
  • 2021-01-15 06:29

    Try regular expressions, like this:

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

    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

    0 讨论(0)
  • 2021-01-15 06:33

    to_i will convert any string to an integer, even if it shouldn't:

    "asdf".to_i
    

    which returns 0.

    What you want to do is:

    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
    

    Integer(some_nonnumeric_string) throws an exception if the string cannot be converted to an integer, whereas String#to_i gives 0 in those cases, which is why result.to_i.is_a? Numeric is always true.

    0 讨论(0)
提交回复
热议问题