ruby 1.9.2有一个is_a吗? function?

我用谷歌搜索有一个is_a? 用于检查对象是否为整数的函数。

但我尝试在rails控制台,它不起作用。

我运行了如下代码:

  "1".is_a? 1.is_a? 

我错过了什么?

如果一个字符串实际上是一个整数,那么就没有一个内置函数可以说明,但你可以很容易地创建自己的:

 class String def int Integer(self) rescue nil end end 

这是因为如果字符串无法转换为整数,则内核方法Integer()会抛出错误,并且内联rescue nil会将该错误转换为nil。

 Integer("1") -> 1 Integer("1x") -> nil Integer("x") -> nil 

因此:

 "1".int -> 1 (which in boolean terms is `true`) "1x".int -> nil "x".int -> nil 

您可以更改函数以在真实情况下返回true ,而不是整数本身,但如果您正在测试字符串以查看它是否为整数,那么您可能希望将该整数用于某事! 我经常做这样的事情:

 if i = str.int # do stuff with the integer i else # error handling for non-integer strings end 

虽然如果测试位置的作业冒犯了你,你可以这样做:

 i = str.int if i # do stuff with the integer i else # error handling for non-integer strings end 

无论哪种方式,这种方法只进行一次转换,如果你必须做很多这些,可能是一个显着的速度优势。

[从int?改变了函数名int? to int以避免暗示它应该返回true / false。]

您忘记包含您正在测试的课程:

 "1".is_a?(Integer) # false 1.is_a?(Integer) # true 

我使用正则表达式

 if a =~ /\d+/ puts "y" else p 'w' end 

Ruby有一个名为respond_to的函数? 可用于查看特定类或对象是否具有具有特定名称的方法。 语法是这样的

 User.respond_to?('name') # returns true is method name exists otherwise false 

http://www.prateekdayal.net/2007/10/16/rubys-responds_to-for-checking-if-a-method-exists/

也许这会对你有所帮助

 str = "1" => "1" num = str.to_i => 1 num.is_a?(Integer) => true str1 = 'Hello' => "Hello" num1 = str1.to_i => 0 num1.is_a?(Integer) => true 

我想要类似的东西,但这些都没有为我做过,但是这个做了 – 用“class”:

 a = 11 a.class => Fixnum