1

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}."

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
cwhitt91
  • 87
  • 6
  • 1
    By "...to ensure that the user enters only a number", I assume you mean, "...to ensure that the user enters the string representation of an integer". Being as precise in your language as in your code will pay dividends. – Cary Swoveland Jul 14 '19 at 22:01

2 Answers2

2

The problem are != and == methods.

For a better way to check if a String can be converted to a valid Integer refer to: Test if a string is basically an integer in quotes using Ruby?

You'de better use an if else statement.

If you add an is_integer? method to the String class as shown in the link above (but you do not have to is just a way) you can check like this:

var_string = gets.chomp
if var_string.is_integer?
  do_something
else
  do_something_else
end
1

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
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59