Accept only numeric input

后端 未结 3 730
情深已故
情深已故 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: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.

提交回复
热议问题