Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

10.2. Listing an Object's Methods

Problem

Given an unfamiliar object, you want to see what methods are available to call.

Solution

All Ruby objects implement the Object#methods method. It returns an array containing the names of the object's public instance methods:

	Object.methods
	# => ["name", "private_class_method", "object_id", "new",
	# "singleton_methods", "method_defined?", "equal?", … ]

To get a list of the singleton methods of some object (usually, but not always, a class), use Object#singleton_methods:

	Object.singleton_methods    # => []
	Fixnum.singleton_methods    # => ["induced_from"]

	class MyClass
	  def MyClass.my_singleton_method
	  end

	  def my_instance_method
	  end
	end
	MyClass.singleton_methods    # => ["my_singleton_method"]

To list the instance methods of a class, call instance_methods on the object. This lets you list the instance methods of a class without instantiating the class:

	''.methods == String.instance_methods         # => true

The output of these methods are most useful when sorted:

	Object.methods.sort
	# => ["<", "<=", "<=>", "==", "===", "=~", ">", ">=",
	# "__id__", "__send__", "allocate", "ancestors", … ]

Ruby also defines some elementary predicates along the same lines. To see whether a class defines a certain instance method, call method_defined? on the class or respond_to? on an instance of the class. To see whether a class defines a certain class method, call respond_to? on the class:

 MyClass.method_defined? :my_instance_method # => true MyClass.new.respond_to? :my_instance_method ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required