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
!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."
else
"OUTPUT: a is neither 3, nor 4"
end
puts answer
I understand this could be better to try with Integer(obj) but is there a way to make this work?
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
!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:
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.
You can do it with a ternary as well I think, like so:
def integer?(number)
number.is_a?(Integer) ? "This is a number" : "This is not a number"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.