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
syntax error, unexpected TCONSTANT. expecting keyword then ,
print "Enter Number Please: "
a = gets.chomp.to_i
answer = case a
"OUTPUT: a is 3"
"OUTPUT: a is 4"
when !a.is_a? Integer
"You did not enter a number."
"OUTPUT: a is neither 3, nor 4"
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!" end
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:
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.