简体   繁体   English

测试输入的数字是否不是文本-RUBY

[英]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 所以我用!a.is_a? Integer !a.is_a? Integer . !a.is_a? Integer However my code doesn't seem to work. 但是我的代码似乎不起作用。 I got this error: 我收到此错误:

syntax error, unexpected TCONSTANT. 语法错误,意外的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? 我知道尝试使用Integer(obj)可能会更好,但是有没有办法做到这一点?

There's several things to note here. 这里有几件事要注意。 For one, the result of to_i is always an Integer type value. 首先, to_i的结果始终是整数类型值。 Testing that !a.is_a? Integer 测试!a.is_a? Integer !a.is_a? Integer is redundant as that will never fail. !a.is_a? Integer是多余的,因为它永远不会失败。

You'll also need to remember that the case statement itself makes it very easy to compare to classes: 您还需要记住, case语句本身使得与类进行比较非常容易:

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. 即使when子句相当慷慨,您也可以对其进行限制。 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. 尽管如前所述,这可以减少到when Integer所以其余的都是多余的。

You'll also want to avoid specifying something in the case part, and then later referring to a variable. 您还希望避免在case部分中指定某些内容,然后再引用变量。 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. 如果您要处理复杂的逻辑,请使用一系列的if语句使事情变得清楚。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM