如何在initialize()中使用define_method [英] How to use define_method inside initialize()
本文介绍了如何在initialize()中使用define_method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图在initialize
内使用define_method
,但获得不确定的方法define_method
.我在做什么错了?
Trying to use define_method
inside initialize
but getting undefined_method define_method
. What am I doing wrong?
class C
def initialize(n)
define_method ("#{n}") { puts "some method #{n}" }
end
end
C.new("abc") #=> NoMethodError: undefined method `define_method' for #<C:0x2efae80>
推荐答案
执行以下操作:
class C
def initialize(n)
self.class.send(:define_method,n) { puts "some method #{n}" }
end
end
ob = C.new("abc")
ob.abc
# >> some method abc
Module#define_method
是私有的方法和 class 方法.您无法使用,因为您尝试在C
实例上调用它.您必须在C
上调用它,使用#send
您的情况.
Module#define_method
is a private method and also a class method.Your one didn't work,as you tried to call it on the instance of C
.You have to call it on C
,using #send
in your case.
这篇关于如何在initialize()中使用define_method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文