当处于红宝石顶级定义的方法呢?
题
在顶层,方法定义应导致对Object
私有方法,以及测试似乎证实了这一点:
def hello; "hello world"; end
Object.private_instance_methods.include?(:hello) #=> true
Object.new.send(:hello) #=> "hello world"
然而,下文中也工作在顶层(self.meta
是main
的eigenclass):
self.meta.private_instance_methods(false).include?(:hello) #=> true
看来,hello
方法同时上的主要的eigenclass以及上Object
定义。这是怎么回事?注意,false
参数private_instance_methods
排除从方法列表中的超类方法。
解决方案
首先,这种行为和下面的推理一直存在;这不是什么新1.9。它发生的技术原因是因为main
是特殊的,比任何其他的对象区别对待。有可用的没有花哨的解释:它的行为,那是因为它是这样设计的。
好,但是为什么呢?什么是推理main
很神奇?由于Ruby的设计师松本行弘认为这使语言更好一>有这样的问题:
此对象上是这样的,为什么顶层方法没有取得单的方法, 而不是拉在作为Object类的实例方法 本身 (并因此到所有其他类即多个名称空间污染比 通常意)。这将仍然允许顶级的方法来调用其他 顶级的方法。而如果顶层对象是由被称为 一些 常像主,那么这些方法可以从任何地方叫 同 Main.method(...)。
你真的希望键入 “Main.print” 无处不?
另外在讨论中,他解释说,这是因为他觉得这样的行为方式“的假设是很自然的。”
编辑:
在响应您的评论,你的问题是针对为什么主要的eigenclass似乎报告hello
作为一个私有的实例方法。美中不足的是,没有一个顶级的功能实际上是添加到main
,而是直接Object
。当eigenclasses工作,功能的instance_methods
家庭总是表现得好像eigenclass仍然是原来的类。即,在该类中定义的方法被视为直接在eigenclass限定。例如:
class Object
private
def foo
"foo"
end
end
self.send :foo # => "foo"
Object.private_instance_methods(false).include? :foo # => true
self.meta.private_instance_methods(false).include? :foo # => true
class Bar
private
def bar
"bar"
end
end
bar = Bar.new
bar.send :bar # => "bar"
Bar.private_instance_methods(false).include? :bar # => true
bar.meta.private_instance_methods(false).include? :bar # => true
我们可以直接添加一个方法来main
的eigenclass,虽然。这种比较原始的例子:
def self.hello; "hello world"; end
Object.instance_methods.include? :hello # => false
self.meta.instance_methods.include? :hello # => true
好了,但是如果我们真的想知道一个给定函数的定义eigenclass,而不是原来的类?
def foo; "foo"; end #Remember, this defines it in Object, not on main
def self.bar; "bar"; end #This is defined on main, not Object
foo # => "foo"
bar # => "bar"
self.singleton_methods.include? :foo # => false
self.singleton_methods.include? :bar # => true