0

I need to check whether my variable is an Integer or a String. The code below will just break the loop, without warning me for an illegal character. Can anyone help me to find the mistake?

x = 0
while x == 0        
  name = gets.chomp.capitalize 
  if name.empty?
    puts "No input. Try again"
  elsif name.is_a? Integer
    puts "Illegal character: Integer "
  else 
    x = 1 
  end               
end 
3
  • 3
    Possible duplicate of How to check if a variable is a number or a string? Commented Dec 10, 2016 at 16:29
  • Do you want to have your string completely without digits? A string like "asdfg09qwerty" would be valid to you or not? Commented Dec 10, 2016 at 17:23
  • 1
    elsif name.is_a? Integer will always return false because name is a string. :-) Commented Dec 10, 2016 at 18:36

2 Answers 2

3

Because gets returns a string you need to find out if the string represents a number (and only a number).

First, translate your string to an integer with to_i. Please note that to_i returns 0 for strings that do not include numbers. In a second step check if translating this integer back into a string matches the original string

 string.to_i.to_s == string

Note that this is just a simple example, it wouldn't work for example with the string 00.

Another way might be checking if the string only contains numbers. That could be done by using a regexp:

string.match(/\A\d+\z/)
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this:

loop do
  puts "Enter name"
  name = gets.chomp
  if name.empty?
    puts "No input, try again"
  elsif name.scan(/\d+/).any?
    puts "Illegal character: Integer"
  else
    raise StopIteration
  end
end

case-expression

Or use a case-expression to tidy things up.

loop do
  puts "Enter name"
  case gets.chomp
  when ''
    puts "No input, try again"
  when /\d/
    puts "Illegal character: Integer"
  else
    raise StopIteration
  end
end

See String#scan, Array#any? and StopIteration for further details

4 Comments

match is preferable here to scan. See Spickermann's answer.
What's up with the two accounts? :)
@SergioTulentsev I guess one was to remain anonymous and one was more 'public' with my real name. Never really used my anonymous one until a few days back when I thought I'd testdrive a new username iceツ. It certainly was not for any illicit reasons (0 votes cast). Anyhow, thought better of keeping both accounts and in the process of merging, but will keep this username for now:)
Oh no, I wasn't implying any shady activity on your part. Just being curious :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.