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

Metaprogramming Intro

In this page:

  1. Metaprogramming Intro

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
🔒

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.