Metaprogramming Basics

Lesson 16 of 20

Peek under the hood: call methods by name with send, write methods at runtime with define_method, and catch unknown calls with method_missing.

The big picture

Code that writes code

Metaprogramming means the program treats its own methods as data — looking them up by name, building them on the fly, and fielding calls that were never defined.

Messages and Methods

Every call is a message sent to an object — Ruby just normally resolves it immediately.

send Calls by Name

obj.send(:name) invokes the method named by a Symbol you computed at runtime.

define_method Builds

define_method(:hi) { } installs a brand-new method while the program is running.

method_missing Catches

When nothing matches the message, method_missing gets one last chance to answer.