← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 6 of 6

Metaprogramming Intro

Metaprogramming is code that writes or changes other code while the program runs, like a robot that can build new robot arms for itself. It lets Ruby be very flexible.

In this page:

  1. Metaprogramming Intro
Syntax
ruby
class ClassName
  define_method(:method_name) { |arg| expression }
end

object.send(:method_name, argument)
object.respond_to?(:method_name)

Metaprogramming Intro

Ruby's metaprogramming lets code define or modify methods and classes at runtime, using tools like define_method, send, and class_eval. This is what powers many popular Ruby gems' expressive, seemingly "magic" APIs.

Metaprogramming is powerful but should be used deliberately -- overusing it can make code much harder to read and debug than straightforward, explicit code.

Note: define_method is often a safer, more debuggable metaprogramming tool than method_missing when you know the method names ahead of time.

Example: Metaprogramming Intro

markup
class Product
  %w[name price category].each do |attribute|
    define_method(attribute) do
      instance_variable_get("@#{attribute}")
    end

    define_method("#{attribute}=") do |value|
      instance_variable_set("@#{attribute}", value)
    end
  end
end

p = Product.new
p.name = "Notebook"
p.price = 4.99

puts p.name
puts p.price
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using instance_variable_get("name") without the @, which raises NameError.
  2. Using define_method and expecting it to define methods on the wrong class because of the self context.
  3. Writing metaprogramming where a simple attr_reader is enough.
Chapter Summary
  • Idiomatic Ruby, frozen string literals, and choosing symbols versus strings lead to cleaner code.
  • Only nil and false are falsy in Ruby.
  • method_missing and metaprogramming are introduced as advanced features.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.