The Object and Module classes define a number of methods for listing, querying, invoking, and defining methods. We’ll consider each category in turn.

Listing and Testing For Methods

Object defines methods for listing the names of methods defined on the object. These methods return arrays of methods names. Those name are strings in Ruby 1.8 and symbols in Ruby 1.9:

o = "a string"
o.methods                # => [ names of all public methods ]
o.public_methods         # => the same thing
o.public_methods(false)  # Exclude inherited methods
o.protected_methods      # => []: there aren't any
o.private_methods        # => array of all private methods
o.private_methods(false) # Exclude inherited private methods
def o.single; 1; end     # Define a singleton method
o.singleton_methods      # => ["single"] (or [:single] in 1.9)

It is also possible to query a class for the methods it defines rather than querying an instance of the class. The following methods are defined by Module. Like the Object methods, they return arrays of strings in Ruby 1.8 and arrays of symbols in 1.9:

String.instance_methods == "s".public_methods                # => true
String.instance_methods(false) == "s".public_methods(false)  # => true
String.public_instance_methods == String.instance_methods    # => true
String.protected_instance_methods       # => []
String.private_instance_methods(false)  # => ["initialize_copy",
                                        #     "initialize"]

Recall that the class methods of a class or module are singleton methods of the Class or Module object. So to list class methods, use Object.singleton_methods ...

Get The Ruby Programming Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.