让class Example
定义为:
class Example
def initialize(test='hey')
self.class.send(:define_method, :say_hello, lambda { test })
end
end
打Example.new; Example.new
我就得到warning: method redefined; discarding old say_hello
.我的结论是,这一定是因为它在实际类中定义了一个方法(从语法上讲,这是有意义的).当然,如果Example
的方法中有多个具有不同值的实例,这将是灾难性的.
有没有一种方法可以仅从实例内部为类的实例创建方法?