Metaprogramming Techniques | 29
TheObject#methodsmethod returns an array of instance methods, including single-
ton methods, defined on the receiver. If the first parameter tomethodsisfalse, only
the object’s singleton methods are returned.
class C
def inst_method
end
def self.cls_method
end
end
c = C.new
class << c
def singleton_method
end
end
c.methods - Object.methods # => ["inst_method", "singleton_method"]
c.methods(false) # => ["singleton_method"]
Module#instance_methodsreturns an array of the class or module’s instance methods.
Note thatinstance_methodsis called on the class, whilemethodsis called on an
instance. Passingfalse toinstance_methods skips the superclasses’ methods:
C.instance_methods(false) # => ["inst_method"]
We can also use Metaid’smetaclass method to examineC’s class methods:
C.metaclass.instance_methods(false) # => ["new", "allocate", "cls_method",
"superclass"]
In my experience, most of the value from these methods is in satisfying curiosity.
With the exception of a few well-established idioms, there is rarely a need in produc-
tion code to reflect on an object’s methods. Far more often, these techniques can be
used at a console prompt to find methods available on an object—it’s usually
quicker than reaching for a reference book:
Array.instance_methods.grep /sort/ # => ["sort!", "sort", "sort_by"]
ObjectSpace
ObjectSpaceis a module used to interact with Ruby’s object system. It has a few use-
ful module methods that can make low-level hacking easier:
- Garbage-collection methods:define_finalizer(sets up a callback to be called
just before an object is destroyed),undefine_finalizer(removes those call-
backs), andgarbage_collect (starts garbage collection). - _id2ref converts an object’s ID to a reference to that Ruby object.
- each_objectiterates through all objects (or all objects of a certain class) and
yields them to a block.