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

后端 未结 5 1497
别那么骄傲
别那么骄傲 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:48

    to_i is fine but all depends on what You want in case of garbage input. Nil ? the you could use integer(value) and rescue if it's not a integer, the same with Float If you want 693iirum5 to return something else you could parse the string entered and you will need a regex to check the string. Since you ask not to give a regex i won't, perhaps you can clearify what you really want it to return.

提交回复
热议问题