Skip to Content
The Ruby Programming Language
book

The Ruby Programming Language

by David Flanagan, Yukihiro Matsumoto
January 2008
Beginner to intermediate
446 pages
14h 45m
English
O'Reilly Media, Inc.
Content preview from The Ruby Programming Language

Methods

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Metaprogramming Ruby 2

Metaprogramming Ruby 2

Paolo Perrotta

Publisher Resources

ISBN: 9780596516178Supplemental ContentErrata Page