Accept only numeric input

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

提交回复
热议问题