Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 134 ยท Metaprogramming

Reflection and Introspection

Learn Ruby introspection: list methods and instance variables, check ancestors, use Method and UnboundMethod objects and find a method with source_location.

Introspection is a program asking questions about itself: what methods does this object have? what class is it? where was this method defined? Reflection goes one step further and uses the answers to act. Ruby makes both very easy, because everything is an object and every object can describe itself. Debuggers, documentation tools, serializers, test frameworks and the irb console are built on these calls.

You will learn how to ask about methods, instance variables, classes and modules, how Method and UnboundMethod objects work, how to find where a method was defined, and which of these tools are fine for everyday code and which should stay in debugging.

Asking an object about its class and ancestry

Ruby Class, ancestors and kinds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

class returns the object's class and superclass its parent. ancestors lists the exact order Ruby searches for methods (the class, included modules, then the parent and so on). Remember the difference between is_a? (true for any ancestor, including modules) and instance_of? (true only for the exact class). Classes and modules are objects too: Dog.class is Class and Walkable.class is Module.

Listing methods

Ruby What methods does an object have?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The false argument means "only methods defined in this class, not inherited ones". Without it you get hundreds of entries from Object and Kernel. The family is: instance_methods (public and protected), public_instance_methods, protected_instance_methods, private_instance_methods for a class, and methods, public_methods, private_methods for an object. singleton_methods lists class-level and per-object methods. respond_to?(name, true) includes private methods.

A neat trick for exploring is to subtract: object.methods - Object.instance_methods shows only what is special about this object, sorted if you want a stable list.

Instance variables and class variables

Ruby Peeking at state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

instance_variable_get and _set read and write state without any accessor method, which is why serializers and test helpers love them and why you should never use them in ordinary business logic: they bypass the object's interface. An unset variable simply returns nil. Use instance_variable_defined? to tell "unset" from "set to nil". The variable name must start with @; otherwise Ruby raises NameError.

A tiny generic "to hash" function shows a legitimate use:

Ruby A generic object-to-hash helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Method objects: methods as values

obj.method(:name) returns a Method object bound to obj. You can call it, pass it around, inspect its parameters and even turn it into a block with &.

Ruby Method objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

parameters is the heart of many frameworks: it tells you the names and kinds (:req, :opt, :key, :keyreq, :rest, :block) of the arguments, so a dependency-injection container or a test runner can call a method with the right inputs. arity is a number: a negative value means optional arguments exist (here it prints -2: one required argument plus optional keywords). The &greeter.method(:greet) form uses the method as a block, so it is the cleanest way to hand an existing method to map or each. Methods also compose: m1 >> m2 and m1 << m2 chain them.

UnboundMethod: a method without an object

Klass.instance_method(:name) returns an UnboundMethod, a method detached from any receiver. You attach it to an object with bind (or bind_call) later. It must be bound to an instance of the same class (or a subclass).

Ruby UnboundMethod and bind (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Calling Animal's speak on a Dog works, even though Dog overrides it: you run the parent's version explicitly. Binding to something unrelated is rejected: the last line ends the program with main.rb:19:in 'UnboundMethod#bind': bind argument must be an instance of Animal (TypeError). This ability to hold a method and apply it later is what wrapper techniques use (see define_method and monkey patching).

Where was it defined? source_location and friends

Which file and line define a method? source_location answers it, and owner tells you which class or module holds it. These two make "where does this method come from?" a one-line question, which is invaluable with deep inheritance, mixins and gems.

Ruby Finding where methods come from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

source_location returns ["main.rb", line] for methods written in Ruby, and nil for methods implemented in C (all the core ones, such as puts). super_method gives the method this one would call with super, or nil when there is none. In a real project you would use method(:x).source_location and then open that file; in a console, the show-source command of IRB or Pry does the same.

Classes and modules as data

Reflection also covers constants, nesting and class relationships.

Ruby Walking the class tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

const_get turns a string into a class, which is how plugin systems and serializers instantiate classes by name (Object.const_get("Shapes::Square")). Only do this with names you trust: a user-supplied string could instantiate any class. Anonymous classes (from Class.new) have no name. subclasses is available from Ruby 3.1.

What an object can tell you about its own methods

Sometimes you want a quick summary of an unfamiliar object. This helper combines several calls. (Run it on your own small classes: on core classes such as Array the method list fills the screen.)

Ruby A mini object inspector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

ObjectSpace: handle with care

ObjectSpace.each_object(Class) iterates over every live object of a kind, and ObjectSpace.count_objects reports internal counts. They can answer "which classes are loaded?", but they are slow, depend on the garbage collector, and are tied to the interpreter. Treat them as debugging tools, never production logic.

Ruby ObjectSpace for debugging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both approaches report ["Gadget"], but only subclasses is stable and fast. Prefer a direct API (or an inherited hook, see hooks) over scanning all of memory.

Use and abuse

Good uses: serializers and inspectors (instance_variables), debugging (source_location, owner, ancestors), test frameworks (finding methods that start with test_), dependency injection (parameters), plugin loading (const_get), and generic helpers (respond_to? checks).

Be careful:

  • Encapsulation. instance_variable_get/set and send ignore private. Use public_send when you should respect visibility.
  • Fragile coupling. Code that depends on the names of another class's internal variables breaks when it is refactored.
  • Performance. methods builds large arrays; do not call it in loops.
  • Security. Never pass user input to const_get, send, instance_variable_set or define_method. Check it against an allow-list.
  • Duck typing first. Often respond_to?(:each) is a better check than is_a?(Array), and a plain rescue NoMethodError or simply calling the method is simpler still.

See also Object Equality and to_s and inspect for related object-level behavior.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between is_a?(Walkable) and instance_of?(Dog)?

    is_a? follows the ancestors chain, so it is true for superclasses and modules. instance_of? requires the object's class to match exactly.
  2. 2. What does Robot.instance_methods(false) return?

    The false argument excludes inherited methods. instance_methods returns public and protected ones; private ones have their own method.
  3. 3. What is a Method object good for?

    obj.method(:name) returns a bound Method that you can call, inspect with parameters and arity, or convert to a block.
  4. 4. What does source_location return for a method like puts that is implemented in C?

    Only methods written in Ruby have a file and line. Methods implemented in C return nil.
  5. 5. Why should ObjectSpace.each_object stay a debugging tool?

    Scanning every live object is costly and its results can vary with GC. Use targeted APIs for production logic.

Summary

  • class, superclass, ancestors, is_a? and instance_of? describe where an object sits in the hierarchy.
  • instance_methods(false), singleton_methods, respond_to? and friends list methods; instance_variables with instance_variable_get/set expose state.
  • obj.method(:x) gives a Method (callable, with parameters, arity, owner, source_location); Klass.instance_method(:x) gives an UnboundMethod you bind later.
  • const_get turns names into classes, but never feed it untrusted input.
  • ObjectSpace is for debugging only; prefer direct APIs like subclasses.
  • Reflection bypasses encapsulation: use it for tools and generic code, not ordinary business logic.

Next: Monkey Patching and Safe Alternatives