ruby 1.9.2 有 is_a 吗?功能?
我在谷歌上搜索到有一个 is_a?
函数来检查对象是否是整数。
但我在 Rails 控制台中尝试过,但不起作用。
我运行了如下代码:
"1".is_a?
1.is_a?
我错过了什么吗?
I googled that there is an is_a?
function to check whether an object is an integer or not.
But I tried in rails console, and it doesn't work.
I ran the code like the following:
"1".is_a?
1.is_a?
Did I miss something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您忘记包含您正在测试的类:
You forgot to include the class you were testing against:
没有内置函数来判断字符串是否实际上是整数,但您可以轻松地创建自己的函数:
这是可行的,因为如果字符串不能为整数,则内核方法
Integer()
会抛出错误。转换为整数,并且内联的rescue nil 将该错误转换为nil。因此:
您可以更改函数以在正确的情况下返回
true
,而不是整数本身,但是如果您正在测试字符串以查看它是否是整数,那么您很可能想要使用某个整数!我经常做这样的事情:虽然如果测试位置的分配冒犯了你,你总是可以这样做:
无论哪种方式,这个方法只进行一次转换,如果你必须做很多这样的事情,可能会这样做。具有显着的速度优势。
[将函数名称从
int?
更改为int
以避免暗示它应该只返回 true/false。]There's not a built in function to say if a string is effectively an integer, but you can easily make your own:
This works because the Kernel method
Integer()
throws an error if the string can't be converted to an integer, and the inlinerescue nil
turns that error into a nil.and thus:
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:Although if the assignment in a test position offends you, you can always do it like this:
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.
[Changed function name from
int?
toint
to avoid implying it should return just true/false.]我使用了正则表达式
i used a regular expression
Ruby 有一个名为 respond_to 的函数?可用于查看特定类或对象是否具有具有特定名称的方法。语法类似于
http ://www.prateekdayal.net/2007/10/16/rubys-responds_to-for-checking-if-a-method-exists/
Ruby has a function called respond_to? that can be used to seeing if a particular class or object has a method with a certain name. The syntax is something like
http://www.prateekdayal.net/2007/10/16/rubys-responds_to-for-checking-if-a-method-exists/
也许这会对你有帮助
Maybe this will help you
我想要类似的东西,但这些都没有为我做到,但这个确实 - 使用“类”:
I wanted something similar, but none of these did it for me, but this one does - use "class":