Metaprogramming (Ruby)

Metaprogramming is writing code that writes or modifies code at runtime — defining methods, opening classes, and responding to messages dynamically. Ruby's openness makes it a metaprogramming powerhouse.

Ruby

Because Ruby classes are open and everything is an object, you can reshape programs while they run: define_method generates methods from data, send calls a method by name (even private ones), instance_variable_get/set pokes at state, and method_missing catches undefined calls. Classes can be reopened and extended any time.

This is what powers Ruby's famously expressive libraries. Rails' attribute accessors, ActiveRecord's dynamic finders, and RSpec's readable DSL are all built with metaprogramming, generating methods so you write less boilerplate.

The power comes with responsibility: heavy metaprogramming can make code hard to follow, slower, and tricky to debug because methods don't exist in the source. Reach for it when it removes real duplication or enables a clean DSL — not just to be clever.

Syntax

define_method(:greet) { "hi" }
obj.send(:private_method)

Examples

Ruby

class Robot
  [:beep, :boop].each do |sound|
    define_method(sound) { sound.to_s.upcase }
  end
end

r = Robot.new
puts r.beep
puts r.boop

Output:

BEEP
BOOP

Learn it in a lesson

See also

Back to the Dictionary