How do I introspect things in Ruby?

我与影子孤独终老i 提交于 2019-12-02 18:09:33
rfunduk

Sure, it's even simpler than in Python. Depending on what information you're looking for, try:

obj.methods

and if you want just the methods defined for obj (as opposed to getting methods on Object as well)

obj.methods - Object.methods

Also interesting is doing stuff like:

obj.methods.grep /to_/

To get instance variables, do this:

obj.instance_variables

and for class variables:

obj.class_variables

If you want all the methods that you can call on something than use

>>> x.methods

If you want some help information then call help before its class

>>> help x.class

Help is a wrapper for ri within irb.

If you have an object, and you want to know what methods it responds to, you can run obj.methods (and all of the tricks that thenduks has mentioned on this result.)

If you have a class, you can run klass.methods to see what class methods are availabe, or you can run klass.instance_methods to know what methods are available on instances of that class. klass.instance_methods(false) is useful, becuase it tells you what methods were defined by the class and not inherited.

There's now way to get help text for a method within Ruby the way python does.

There's a module called ObjectSpace which is included into each object created in ruby. It holds all of the methods that help you introspect current context of the process. In irb you begin in Object:Main context which is top level context for current irb session. Then you could do something like time = Time.now and then do irb time which would take you into that object's context and you could inspect it from the inside without calling ObjectSpace methods on that object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!