Mr.*_*ack 0 ruby metaprogramming dynamic
在我的项目中使用的示例模块(n个数字)下面,具有相同的方法名称,具有不同的返回值(带模块名称的前缀).
module Example1
def self.ex_method
'example1_with_'
end
end
module Example2
def self.ex_method
'example2_with_'
end
end
Run Code Online (Sandbox Code Playgroud)
我尝试使用像#define_method这样的元编程方式来实现这一点.但是,这对我不起作用.有什么办法吗?
array.each do |name|
Object.class_eval <<TES
module #{name}
def self.ex_method
"#{name.downcase}_with_"
end
end
TES
end
Run Code Online (Sandbox Code Playgroud)
错误捕捉:你可以在最后一行看到它没有完成.
m = Object.const_set("Example1", Module.new)
#=> Example1
m.define_singleton_method("ex_method") { 'example1_with' }
#=> :ex_method
Run Code Online (Sandbox Code Playgroud)
让我们来看看:
Example1.is_a? Module
#=> true
Example1.methods.include?(:ex_method)
#=> true
Example1.ex_method
#=> "example1_with"
Run Code Online (Sandbox Code Playgroud)