[英]Ruby class_eval method
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? 不幸的是,这仅创建方法m,但是我需要基于m的值来创建方法(想法)?
There are two accepted ways: 接受的方式有两种:
Use define_method : 使用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: 使用class_eval和一个字符串参数:
@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. 第一个选项将闭包转换为方法,第二个选项计算字符串(heredoc)并使用常规方法绑定。 The second option has a very slight performance advantage when invoking the methods.
调用方法时,第二个选项在性能上有很小的优势。 The first option is (arguably) a little more readable.
第一个选项(可以说)更具可读性。
define_method(m) do |*values|
puts value
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.