How do I introspect things in Ruby?

前端 未结 4 954
粉色の甜心
粉色の甜心 2021-01-31 18:57

For instance, in Python, I can do things like this if I want to get all attributes on an object:

>>> import sys
>>> dir(sys)
[\'__displayhook__         


        
4条回答
  •  甜味超标
    2021-01-31 19:10

    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
    

提交回复
热议问题