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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Using
instance_variable_get("name")without the@, which raisesNameError. - Using
define_methodand expecting it to define methods on the wrong class because of theselfcontext. - Writing metaprogramming where a simple
attr_readeris enough.
Chapter Summary
- Idiomatic Ruby, frozen string literals, and choosing symbols versus strings lead to cleaner code.
- Only
nilandfalseare falsy in Ruby. method_missingand metaprogramming are introduced as advanced features.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: