我如何在Ruby中反省内容?

例如,在Python中,如果我想获取对象的所有属性,我可以做这样的事情:

>>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions'] 

或者,如果我想查看某些内容的文档,我可以使用help函数:

 >>> help(str) 

有没有办法在Ruby中做类似的事情?

当然,它比Python更简单。 根据您要查找的信息,请尝试:

 obj.methods 

如果你只想要为obj定义的方法(而不是在Object上获取方法)

 obj.methods - Object.methods 

同样有趣的是做的事情:

 obj.methods.grep /to_/ 

要获取实例变量,请执行以下操作:

 obj.instance_variables 

对于类变量:

 obj.class_variables 

如果你想要所有的方法,你可以调用一些东西而不是使用

 >>> x.methods 

如果您需要一些帮助信息,请在课前致电帮助

 >>> help x.class 

帮助是irb中ri的包装器。

如果你有一个对象,并且你想知道它响应的方法,你可以运行obj.methods (以及theu​​uks在这个结果中提到的所有技巧。)

如果您有一个类,则可以运行klass.methods以查看可用的类方法,或者运行klass.instance_methods以了解该类实例上可用的方法。 klass.instance_methods(false)很有用,因为它告诉你哪些方法是由类定义的而不是inheritance的。

现在有了像python那样在Ruby中获取方法的帮助文本的方法。

有一个名为ObjectSpace的模块,它包含在ruby中创建的每个对象中。 它包含所有可帮助您内省流程当前上下文的方法。 在irb中,您从Object:Main上下文开始,它是当前irb会话的顶级上下文。 然后你可以做一些类似time = Time.now ,然后执行irb time ,这将带你进入该对象的上下文,你可以从内部检查它,而无需在该对象上调用ObjectSpace方法。