liveBook · Manning

Singleton_methods

As explained in The Well-Grounded Rubyist, Fourth Edition

singleton_methods is a Ruby method that returns the public and protected singleton method names available to an object, excluding private singleton methods.

Call singleton_methods on an object to list the names of its public and protected singleton methods. Private singleton methods are omitted. A singleton method belongs only to one object, or, when that object is a class, to the class and its subclasses. section 15.2.4

Use singleton_methods to inspect where object-specific behavior comes from:

  • c.singleton_methods returns inherited singleton methods as well as methods defined directly on c's singleton class. section 15.2.4
  • c.singleton_methods(false) restricts the result to singleton methods defined directly on c. section 15.2.4
  • For a class, singleton_methods can reveal class methods inherited from ancestor classes; related class-level queries inspect visibility on the singleton class. section 7.7.3 section 15.2.4

Visibility filtering

class C end c = C.new class << c def x; end def y; end def z; end protected :y private :z end p c.singleton_methods.sort # [:x, :y] The private method z remains an instance method of c's singleton class, but singleton_methods does not report it.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains singleton classes, visibility filtering, and inherited results, while stopping short of broader method lookup internals.
Examples
Uses a singleton class containing public, protected, and private methods, plus inherited class methods and File-versus-IO comparisons.
What it assumes
Assumes familiarity with objects, classes, method visibility, inheritance, and singleton classes.
What you can do after
Diagnose which public and protected singleton methods an object or class defines directly or inherits.
How it connects
Connects singleton methods with singleton classes, class methods, method visibility, inheritance, and runtime introspection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.