Metaprogramming Intro
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: