How to cleanly verify if the user input is an integer in Ruby?

后端 未结 5 1510
别那么骄傲
别那么骄傲 2021-01-02 02:18

I have a piece of code where I ask the user to input a number as an answer to my question. I can do to_i but tricky/garbage inputs would escape through to

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 02:57

    This will do to validate the input:

    Integer(gets) rescue nil
    

提交回复
热议问题