Ruby class_eval method
ruby
Solution
There are two accepted ways:
Use define_method:
@arr.each do |method|
self.class.class_eval do
define_method method do |*arguments|
puts arguments
end
end
end
Use class_eval with a string argument:
@arr.each do |method|
self.class.class_eval <<-EVAL
def #{method}(*arguments)
puts arguments
end
EVAL
end
The first option converts a closure to a method, the second option evaluates a string (heredoc) and uses regular method binding. The second option has a very slight performance advantage when invoking the methods. The first option is (arguably) a little more readable.
Problem
I'm trying to figure out how to dynamically create methods ``` class MyClass def initialize(dynamic_methods) @arr = Array.new(dynamic_methods) @arr.each { |m| self.class.class_eval do def m(*value) puts value end end } end end tmp = MyClass.new ['method1', 'method2', 'method3'] ``` Unfortunately this only creates the method m but I need to create methods based on the value of m, ideas?