define_method是Module的一种方法。
在Ruby2.0中,define_method可以在顶层使用;它不必在类或模块中。
define_method :kick do
puts "method"
end在Ruby1.9中,main对象没有define_method方法。
define_method :kick
# => NoMethodError: undefined method `define_method' for main:ObjectRuby 2.0是如何实现这一点的?
发布于 2014-02-04 09:47:45
我也对这个特性很好奇,并使用irb来尝试一下。请看一下:
% irb
2.0.0-p353 :001 > method(:define_method)
=> #<Method: main.define_method>
2.0.0-p353 :002 > private_methods(false)
=> [:public, :private, :include, :using, :define_method, :irb_exit_org, :default_src_encoding, :irb_binding]
2.0.0-p353 :003 > singleton_class.private_instance_methods(false)
=> [:public, :private, :include, :using, :define_method, :irb_exit_org] 它表明define_method是主对象(顶层自身)的私有单例方法。
发布于 2014-06-26 10:00:37
define_method()建立在uncutstone的侦察基础上,不会被main的单例类继承:
class <<self
p private_instance_methods(false)
end
--output:--
[:public, :private, :include, :using, :define_method]...and据我所知,如果一个方法没有被继承,就必须在类中定义它。请注意,当您包含一个模块时,ruby会创建一个匿名类并在匿名类中插入模块的defs,然后在方法查找链中将匿名类直接插入到包含类的上方,例如:
module A
def greet
puts 'hi'
end
end
class Dog
include A
end
p Dog.instance_methods(false)
p Dog.instance_methods.grep(/^g/)
--output:--
[]
[:greet]输出显示greet()是一个继承的方法。但是因为define_method()不是由main的单例类继承的,所以不能通过包含一个模块来获得define_method()。相反,define_method()似乎必须是在main的单例类中定义的。因此,实现这一点的一种方法是让ruby解释器在解析代码之前执行以下代码:
class <<self
def define_method(x, *y)
#same code as in Module's define method
end
endhttps://stackoverflow.com/questions/19053338
复制相似问题