Accept only numeric input

后端 未结 3 738
情深已故
情深已故 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条回答
  •  猫巷女王i
    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

提交回复
热议问题