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

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

    Use Kernel#Integer

    The Kernel#Integer method will raise ArgumentError: invalid value for Integer() if passed an invalid value. The method description says, in part:

    [S]trings should be strictly conformed to numeric representation. This behavior is different from that of String#to_i.

    In other words, while String#to_i will forcibly cast the value as an integer, Kernel#Integer will instead ensure that the value is already well-formed before casting it.

    Examples Simulating Behavior of Integer(gets)

    Integer(1)
    # => 1
    
    Integer('2')
    # => 2
    
    Integer("1foo2\n")
    # => ArgumentError: invalid value for Integer(): "1foo2\n"
    

提交回复
热议问题