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 
Ed de Almeida
  • 3,675
  • 4
  • 25
  • 57
  • 3
    Possible duplicate of [How to check if a variable is a number or a string?](http://stackoverflow.com/questions/8616360/how-to-check-if-a-variable-is-a-number-or-a-string) – Naman Dec 10 '16 at 16:29
  • Do you want to have your string completely without digits? A string like "asdfg09qwerty" would be valid to you or not? – Ed de Almeida Dec 10 '16 at 17:23
  • 1
    `elsif name.is_a? Integer` will always return `false` because `name` is a string. :-) – Cary Swoveland Dec 10 '16 at 18:36

2 Answers2

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/)
spickermann
  • 100,941
  • 9
  • 101
  • 131
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

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
  • `match` is preferable here to `scan`. See Spickermann's answer. – Sagar Pandya Dec 10 '16 at 17:17
  • What's up with the two accounts? :) – Sergio Tulentsev Jun 28 '17 at 14:08
  • 1
    @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:) – Sagar Pandya Jun 28 '17 at 15:09
  • 1
    Oh no, I wasn't implying any shady activity on your part. Just being curious :) – Sergio Tulentsev Jun 28 '17 at 15:11