Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 134 ยท Metaprogramming

define_method and Dynamic Methods

Learn how Ruby define_method creates methods at runtime, how to write attr-like class macros, how closures capture values, and when plain def is better.

Normally you write a method with def, and its name is fixed when you type the code. Sometimes that is tedious: ten similar methods that differ only in a name, or methods whose names come from data. Ruby lets a program create methods while it runs. The main tool is define_method, which takes a name and a block and turns the block into a real, ordinary method.

This lesson shows how define_method works, how to use it in loops and in your own class-level "macros" (the way attr_accessor works), how the block's closure behaves, and where define_method is the wrong choice. It builds on blocks, closures and class methods, and it is the cleaner alternative to method_missing when the names are known.

The idea in one example

Ruby Your first dynamic method

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.

define_method(:hello) { ... } produces exactly what def hello ... end would: a public instance method that shows up in instance_methods and answers respond_to?. The block's parameters become the method's parameters, and they support defaults, keywords, splats and a block parameter. The value of the last expression is the return value.

Inside a class body, self is the class, so define_method(:hello) is a call to Greeter.define_method. Since Ruby 2.5 it is a public method, so you can also call it from outside: Greeter.define_method(:later) { ... }.

Generating many methods in a loop

The classic reason to use define_method is repetition. Suppose a traffic light has three colors and you want a predicate for each: red?, yellow? and green?.

Ruby One method per color

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.

Two details matter here. First, the method name is built with an interpolated symbol, :"#{name}?". Second, the loop variable name is captured by the block, so each of the three methods remembers its own color. That is closure behavior: a def would not see name at all, because def starts a fresh scope, while a block sees the variables around it.

A def is a "scope gate": local variables from outside are not visible inside it. A block is not a gate. That single difference is why define_method can use outer variables and def cannot.

Closures: each method keeps its own state

Because the method body is a closure, you can create methods that carry private state, even state shared between several methods.

Ruby Methods that share a captured variable

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 objects print 3. The local variable count lives in the class body and both blocks close over the same variable, so every instance of Counter shares it. That is occasionally useful and often surprising, so use instance variables (@count) for per-object state. Capturing is best for constants of the generation step, such as the field name or a default.

Attr-like class macros

attr_accessor :name looks like syntax, but it is a normal class method that defines methods. You can write your own. Define a method on the class (with def self.) that calls define_method, and call it from the class body. Such a class-level helper is called a macro.

Ruby A typed attribute macro

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 last line ends the program with main.rb:9:in 'block in Product#attribute': price must be Numeric, got String (TypeError), with a second backtrace line pointing at your own item.price = "free" call. The macro runs once per attribute line, creating a getter and a setter whose behavior depends on the arguments. Because Product inherits from Model, attribute is available in its body; this pattern is the heart of ORMs, serializers and validation libraries.

Notice instance_variable_get("@#{name}"): dynamic methods usually read and write state through instance_variable_get and instance_variable_set, since the variable name is only known at runtime. See Reflection and Introspection for these.

Defining methods on one object or on the class of a class

define_method always defines an instance method of the receiver. If you need a method on a single object (a singleton method) or a class method, define it on the singleton class.

Ruby Singleton and class methods, dynamically

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.

define_singleton_method is the shortcut: it defines the method on an object's singleton class. On a class object it creates a class method. The longer spelling, singleton_class.define_method(...), does the same.

Using methods you already have

define_method accepts a second form: instead of a block you can pass a Method, an UnboundMethod or a lambda. That makes aliases and wrappers easy.

Ruby Wrapping an existing method

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_method(name) fetches the old definition as an UnboundMethod. Then the new definition calls it with bind(self), so the original runs on the right object, and adds logging around it. This is the manual form of what a prepend wrapper does; see Monkey Patching and Safe Alternatives for the safer module-based version.

Arguments: define_method is lambda-like

The block you pass behaves like a lambda, not like a plain block: it checks the number of arguments, and return leaves the method.

Ruby Strict arity (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.

The last call ends the program with main.rb:2:in 'block in <class:Demo>': wrong number of arguments (given 1, expected 2) (ArgumentError), just like a method defined with def. A regular block given to each would instead fill the missing argument with nil. The return inside early returns from the method, too.

One more thing to know: methods created by define_method can be a little slower to call than def methods, because the block runs as a closure. In practice the difference only matters in extremely hot loops.

Visibility of generated methods

A method made by define_method is public unless you say otherwise. If you call define_method directly in the class body after a bare private, it does become private. But when the call happens inside a class macro, the earlier private does not reach it: the setting belongs to the scope where you typed it, so the macro's methods stay public. The robust rule is to be explicit and pass the name to private.

Ruby Making dynamic methods private

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.

private name (with an argument) changes the visibility of an existing method. Inside the class, reveal can still call pin and token, but acct.pin from outside fails with private method 'pin' called for an instance of Account (NoMethodError). More on this in Method Visibility.

define_method versus def, Struct and method_missing

Situation Best tool
A fixed handful of methods Plain def, easiest to read and search
Many methods that differ only in a name or constant define_method in a loop
Value objects with named fields Struct or Data
Names unknown until runtime method_missing, with respond_to_missing?
Methods from a library DSL (validations, associations) A class macro built on define_method

Pitfalls professionals know

  • Debuggability. A stack trace through a generated method says block in Model.attribute, not the line of your attribute :price. Keep generated bodies short and give errors informative messages.
  • Searchability. Nobody can grep for red? if it is built from "#{name}?". Add a comment or documentation near the macro that lists the generated names.
  • Name collisions. define_method silently replaces an existing method of the same name in that class. Check with method_defined? when it matters.
  • Variable capture. Blocks capture variables, not values. If a loop variable is reassigned later, every method would see the final value. Each iteration of each gets its own block variable, so the loop forms in this lesson are safe; a while loop with an outer counter is not.
  • Security. Never build method names from untrusted input, such as user-submitted parameters. Match against a whitelist first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does define_method(:ping) { 'pong' } create inside a class body?

    define_method defines an instance method of the receiver (here, the class). It is public unless you change its visibility.
  2. 2. Why can a define_method block use a local variable from the surrounding code while a def method cannot?

    A block closes over the variables around it. The def keyword is a scope gate, so outer local variables are invisible inside it.
  3. 3. You call d.pair(1) on a method created with define_method(:pair) { |a, b| ... }. What happens?

    The block of define_method is lambda-like, so it checks its arity just like a def method.
  4. 4. Which call defines a method on one single object only?

    define_singleton_method defines the method on the singleton class of that one object. On a class it creates a class method.
  5. 5. When is plain def the better choice than define_method?

    Use metaprogramming only when it removes real repetition. For a few fixed methods, def is simpler to read and to debug.

Summary

  • define_method(name) { |args| ... } creates a real instance method at runtime, with the block's parameters.
  • Loops and class macros (def self.attribute) turn define_method into attr-like helpers.
  • The block is a closure, so generated methods can capture variables; use instance variables for per-object state.
  • define_singleton_method defines a method on one object or on a class (a class method).
  • The block acts like a lambda: strict arity, and return leaves the method. Use private name to hide generated methods.
  • Prefer def for a few fixed methods, and keep generated methods searchable and documented.

Next: Hooks and Callbacks