检查字符串是否是ruby中的字符串

时间:2018-04-05 18:48:36

标签: ruby

我想检查用户输入的字符串。如果是字符串,则移动,如果不是,则抛出错误。我不知道如何检查用户输入是字符串还是int。以下是我的代码:

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"

2 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西。

 if name.class == String

这也总是假的

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

年龄总是一个整数她,因为你已经用.to_i

投了它

答案 1 :(得分:0)

可以这样检查:

  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