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

后端 未结 5 1471
别那么骄傲
别那么骄傲 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.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-01-02 02:57

    This will do to validate the input:

    Integer(gets) rescue nil
    
    0 讨论(0)
  • 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   
    
    0 讨论(0)
  • 2021-01-02 03:02

    In answer to camdixon's question, I submit this proposed solution.

    Use the accepted answer, but instead of rescue nil, use rescue false and wrap your code in a simple if.

    Example

    print "Integer please: " 
    user_num=Integer(gets) rescue false 
    if user_num 
        # code 
    end
    
    0 讨论(0)
提交回复
热议问题