Ruby's dynamic method creation is a powerful metaprogramming feature that allows developers to add methods to classes at runtime. This flexibility enables writing more concise and adaptable code.
Dynamic method creation involves defining methods programmatically during execution, rather than statically in the class definition. This technique is part of Ruby's Ruby Metaprogramming capabilities.
The primary method for dynamic method creation is define_method
. It takes a symbol representing the method name and a block that defines the method's behavior.
class MyClass
define_method :greet do |name|
puts "Hello, #{name}!"
end
end
obj = MyClass.new
obj.greet("Ruby") # Output: Hello, Ruby!
Dynamic method creation is particularly useful in scenarios where:
Here's a more complex example demonstrating how to generate getter methods for a class:
class Person
def initialize(attributes)
@attributes = attributes
attributes.each do |key, value|
self.class.define_method(key) { @attributes[key] }
end
end
end
person = Person.new(name: "Alice", age: 30)
puts person.name # Output: Alice
puts person.age # Output: 30
To further explore Ruby's metaprogramming capabilities, consider learning about:
Dynamic method creation is a powerful tool in Ruby's metaprogramming arsenal. When used appropriately, it can lead to more flexible and expressive code. However, it's important to balance its use with code clarity and maintainability.