-1

I want to check a string entered by a user. If it is a string, then move along, if not, then throw an error. I do not know how to check if the user input is a string or an int. Below is my code:

puts "what is your name?"
name = gets.chomp
if name == Int
puts "error enter a string"
end
if birthdate != Int
puts "error enter your birthdate"
end
puts "how old are you "
age = gets.to_i
if age == String
puts "error please enter your age"
end

puts "hello"  + name + " wow that is a good day to be born" + "thats a great age"
puts "the half  of your age is #{age/2.0} that is good to know"
sawa
  • 165,429
  • 45
  • 277
  • 381
J1N1
  • 39
  • 1
  • 1
  • 7
  • 5
    [Kernal#gets](http://ruby-doc.org/core-2.4.0/Kernel.html#method-i-gets) returns a string, even when it looks like some other object. For example, if `gets.chomp #=> "1"` (the user entered `"1"`), it is still a string, not an integer. Perhaps you want to know if the user has entered the string representation of a Ruby object other than a string (e.g., `"1"`, `":cat"`, `"[1,2,3]"`, `"{ :a=>1 }"`), – Cary Swoveland Apr 05 '18 at 19:00
  • Have a look at this https://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails, and the answer by @hipertracker is what you want I think. – sameera207 Apr 05 '18 at 21:32
  • What is your question? – sawa Apr 06 '18 at 04:07

2 Answers2

0

I think this is what you are looking for.

 if name.class == String

Also this will always be false

age = gets.to_i  # this is converting to integer
if age.class == String # I think this is what you meant

age will always be an Integer her because you have cast it as such with .to_i

Nick Ellis
  • 1,048
  • 11
  • 24
  • 1
    Also there is_a? function in ruby. https://apidock.com/ruby/Object/is_a%3F – Nick Ellis Apr 05 '18 at 20:03
  • When string value enter for age, its value will be `0` since it cast to integer. – Ashik Salman Apr 06 '18 at 04:44
  • Thank you all for the response, for the age I want it to be a number so if I type age.class == INT will it be the same as saying name,class == String ? I basically want the code to see if someone entered in a string where it should be an int then throw an error thats why on the if statements I typed age = string and name = int so on – J1N1 Apr 06 '18 at 12:00
0

It may be checked as this:

  puts "what is your name?"
  name = gets.chomp
  if !(name =~ /[0-9]/).nil?
   puts "error enter a string"
  end
  puts "what is your age?"
  age = gets.chomp
  if age.to_i.to_s == age
   puts "error enter a integer"
  end
Rajath H R
  • 16
  • 2