ruby 1.9.2 有 is_a 吗?功能? [英] Does ruby 1.9.2 have an is_a? function?
问题描述
我在谷歌上搜索到有一个 is_a?
函数来检查一个对象是否是一个整数.
I googled that there is an is_a?
function to check whether an object is an integer or not.
但是我在 rails 控制台中尝试过,它不起作用.
But I tried in rails console, and it doesn't work.
我运行的代码如下:
"1".is_a?
1.is_a?
我错过了什么吗?
推荐答案
没有内置函数来说明字符串是否有效地是整数,但您可以轻松地创建自己的:
There's not a built in function to say if a string is effectively an integer, but you can easily make your own:
class String
def int
Integer(self) rescue nil
end
end
这是有效的,因为内核方法 Integer()
在字符串不能转换为整数时抛出错误,并且内联 rescue nil
将该错误转换为一个零.
This works because the Kernel method Integer()
throws an error if the string can't be converted to an integer, and the inline rescue nil
turns that error into a 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
,而不是整数本身,但是如果您正在测试字符串以查看它是否为整数,则您可能想要使用那个整数的东西!我经常做这样的事情:
You could alter the function to return true
in the true cases, instead of the integer itself, but if you're testing the string to see if it's an integer, chances are you want to use that integer for something! I very commonly do stuff like this:
if i = str.int
# do stuff with the integer i
else
# error handling for non-integer strings
end
尽管如果考试职位的作业冒犯了您,您也可以这样做:
Although if the assignment in a test position offends you, you can always do it like this:
i = str.int
if i
# do stuff with the integer i
else
# error handling for non-integer strings
end
无论哪种方式,这种方法都只进行一次转换,如果您必须进行大量转换,这可能是一个显着的速度优势.
Either way, this method only does the conversion once, which if you have to do a lot of these, may be a significant speed advantage.
[将函数名称从 int?
更改为 int
以避免暗示它应该只返回 true/false.]
[Changed function name from int?
to int
to avoid implying it should return just true/false.]
这篇关于ruby 1.9.2 有 is_a 吗?功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!