rubyif-statementintegerflow-control

How to use flow control to request the user inputs an integer as opposed to a string


My program asks a user for a number. I'm working with flow control to ensure that the user enters only a number, and if the user enters anything other than a number, the program prompts the user to "Please enter a number". Even when the user enters a number, the flow control statement asking the user to "Please enter a number" runs.

I'm not getting any error messages, but one of my if/else statements must have inappropriate syntax. I've done research about what "variable" should be set to to achieve the desired output, but I must not have the appropriate boolean value.

puts "Enter a number."
variable = gets.chomp
variable = variable.to_i

if variable != Integer
 puts "Please enter a number."
elsif variable == Integer 
 puts "Thank you. Your number is #{variable}."
end

Even when I actually enter a number in the terminal, I only get "Please enter a number." I expect that when I enter a number, I will get "Thank you. Your number is #{variable}."


Solution

  • The only way to compare Integer and get true is comparing Integer with Integer:

    Integer == Integer
    # true
    

    What you need in that case is to use Object#is_a? which returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj:

    module M;    end
    class A
      include M
    end
    class B < A; end
    class C < B; end
    
    b = B.new
    b.is_a? A          #=> true
    b.is_a? B          #=> true
    b.is_a? C          #=> false
    b.is_a? M          #=> true
    

    That allows you to check if the object is Integer "based", but, notice that you're redefining variable to its to_i version, which will return an Integer always.

    You could use String#match to check if the value entered by the user matches a number (positive or negative Integer):

    unless variable.match?(/^-?\d*$/)
      ...
    end