Mikk Poles Mikk Poles - 1 year ago 69
Ruby Question

Test if the number input is not a text - RUBY

I tried to create a program that will test if the inserted input is a text or a number or special character. So I used

!a.is_a? Integer
. However my code doesn't seem to work. I got this error:

syntax error, unexpected TCONSTANT. expecting keyword then ,

Here's my code:

print "Enter Number Please: "
a = gets.chomp.to_i

answer = case a

when 3
"OUTPUT: a is 3"
when 4
"OUTPUT: a is 4"
when !a.is_a? Integer
"You did not enter a number."
"OUTPUT: a is neither 3, nor 4"

puts answer

I understand this could be better to try with Integer(obj) but is there a way to make this work?

Answer Source

There's several things to note here. For one, the result of to_i is always an Integer type value. Testing that !a.is_a? Integer is redundant as that will never fail.

You'll also need to remember that the case statement itself makes it very easy to compare to classes:

case (a)
when Integer
  puts "I'm a number!"
when String
  puts "I'm a string!"

Note that the first condition is automatically triggered for any Integer values.

There's limits on what you can put in a when clause even if they are fairly generous. To get the parser to properly interpret what you're asking for, you'd have to express it like this:

when !a.is_a?(Integer)

Though as noted this can be reduced down to when Integer so the rest of that is redundant.

You'll also want to avoid specifying something in the case part, and then later referring to a variable. It's confusing to anyone reading your code and probably unnecessary. If you're dealing with complicated logic, use a series of if statements to make things clear.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download