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

后端 未结 5 1506
别那么骄傲
别那么骄傲 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 03:01

    Use input_string.to_i.to_s == input_string to verify whether the input_string is an integer or not without regex.

    > input_string = "11a12"
    > input_string.to_i.to_s == input_string
    => false
    > input_string = "11"
    > input_string.to_i.to_s == input_string
    => true
    > input_string = "11.5"
    > input_string.to_i.to_s == input_string
    => false   
    

提交回复
热议问题