Introduction
Metaprogramming lets Ruby programs write or change code while running. This makes programs flexible and saves time.
Metaprogramming lets Ruby programs write or change code while running. This makes programs flexible and saves time.
# Example of defining a method dynamically class MyClass define_method(:greet) do |name| "Hello, #{name}!" end end
say_hello dynamically that prints a greeting.class Person define_method(:say_hello) do "Hi!" end end p = Person.new puts p.say_hello
add and subtract dynamically using a loop.class Calculator [:add, :subtract].each do |method_name| define_method(method_name) do |a, b| method_name == :add ? a + b : a - b end end end calc = Calculator.new puts calc.add(5, 3) puts calc.subtract(5, 3)
This program creates a Robot class that gets methods walk, talk, and jump automatically. Each method prints what the robot can do.
class Robot def initialize(name) @name = name end ['walk', 'talk', 'jump'].each do |action| define_method(action) do "#{@name} can #{action}!" end end end r = Robot.new('Robo') puts r.walk puts r.talk puts r.jump
Metaprogramming can make code harder to read if overused, so use it carefully.
It helps reduce repeated code and makes programs more flexible.
Metaprogramming lets Ruby programs create or change code while running.
This makes programs flexible, saves time, and reduces repeated code.
Use it to add or change methods automatically based on your needs.
define_method to create methods at runtime.define_method(:greet) { puts 'Hello' }, which is valid Ruby syntax.class Person
def self.create_attr(name)
define_method(name) { @attributes ||= {}; @attributes[name] }
define_method("#{name}=") { |value| @attributes ||= {}; @attributes[name] = value }
end
create_attr :age
end
p = Person.new
p.age = 30
puts p.agecreate_attr defines getter and setter methods for the given attribute name using metaprogramming.create_attr :age, the instance has age and age= methods. Setting p.age = 30 stores 30 in @attributes[:age]. Then puts p.age outputs 30.class Calculator
def self.add_method(name, &block)
define_method(name, &block)
end
add_method(:sum) do |a, b|
a + b
end
end
calc = Calculator.new
puts calc.sum(2, 3)add_method tries to call define_method directly, but define_method is a private instance method of Module, not available in the class method context.define_method inside a class method without proper context causes an error.Pass the test and this pattern moves unknown