liveBook · Manning

Instance_methods

As explained in The Well-Grounded Rubyist, Fourth Edition

instance_methods is a Ruby Module method that returns the public and protected instance methods available from a class or module, optionally including inherited and included methods.

instance_methods is a Ruby Module method for asking a class or module which public and protected instance methods its instances can use. With no argument, it includes methods supplied by the queried object and its ancestors. section 7.7.2 section 15.2.3

Choose the query according to the method set you need:

  • Use instance_methods(false) to restrict the result to methods defined directly by the class or module, excluding ancestors. section 7.7.3
  • Use public_instance_methods, a synonym for instance_methods, or choose protected_instance_methods and private_instance_methods for visibility-specific lists. section 7.7.3 section 15.2.3
  • Use set intersection between two lists to find methods that one class or module defines in common with another. section 15.2.3

Inspecting Range and Enumerable

Range.instance_methods(false).sort lists methods defined directly on Range. Intersecting that list with Enumerable.instance_methods(false) identifies methods such as count, entries, first, include?, max, min, and to_a that Range redefines from Enumerable. section 15.2.3

>> Range.instance_methods(false).sort & 
➥ Enumerable.instance_methods(false)
=> [:count, :entries, :first, :include?, :max, :member?, :min, :minmax,
 :reverse_each, :to_a] 

The executable IRB listing makes direct-definition filtering and method-list intersection concrete. section 15.2.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines inherited and direct-only queries, visibility variants, and list intersection, but stops short of method implementation details.
Examples
Uses String.instance_methods, Enumerable.instance_methods, Range.instance_methods(false), and Enumerable intersection to inspect and compare method sets.
What it assumes
Assumes familiarity with Ruby objects, classes, modules, ancestors, and public, protected, and private visibility.
What you can do after
Diagnose where instance methods come from and identify methods that classes override from included modules.
How it connects
Connects Module, class inheritance, ancestors, method visibility, Enumerable, and undef_method.

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.