如何检查 Ruby 对象的方法?
我想知道是否有一个 Ruby 方法调用仅显示由其调用的 Ruby 对象定义的方法,而不是显示由其祖先类定义的所有方法,这就是 methods
似乎要做的事情。
I am wondering if there is a Ruby method call that shows only the methods defined by the Ruby object it's called from, as opposed to all the methods defined by its ancestor classes, which is what methods
seems to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
methods
采用可选的布尔参数,该参数指定是同时列出对象的类及其超类中的方法,还是仅列出对象的单例方法。因此,您可以执行 obj.methods(false) 来仅获取 obj 上定义的单例方法。如果您想要由对象的类定义的方法,而不是由其超类定义的方法,则可以通过在对象的类上调用
instance_methods(false)
来获取该方法,因此它是obj.class。 instance_methods(假)
。methods
takes an optional boolean parameter, which specifies whether to also list the methods from the object's class and its superclasses or just the object's singleton methods. So you can doobj.methods(false)
to only get the singleton methods defined onobj
.If you want the methods defined by the object's class, but not those defined by its superclasses, you can get that by calling
instance_methods(false)
on the object's class, so it'sobj.class.instance_methods(false)
.我偏向 obj.methods.sort ,但其他一些答案在某些情况下更好,正如它们所描述的那样
您也可以使用 obj.methods.sort.grep /foo/ 查找与正则表达式匹配的方法名称。
当您知道自己要寻找什么时,这会很有帮助。
I'm partial to
obj.methods.sort
but some of the other answers are better in certain cases as they describeYou can also use
obj.methods.sort.grep /foo/
to find method names matching the regexp.This is helpful when you have an idea of what you're looking for.
您有几个选项 -
object.methods
、object.public_methods
、object.singleton_methods
...这取决于您想要什么。由于它们都返回一个数组,您可能想尝试以下操作:You have a few options -
object.methods
,object.public_methods
,object.singleton_methods
... it depends on what you want. Since they both return an array, you might want to try something like: