首先,这种行为和潜在的推理一直存在;这对1.9来说并不是什么新鲜事。它发生的技术原因是
main
有魔力吗?因为Ruby的设计师松本幸弘认为
makes the language better
要具有此行为,请执行以下操作:
那么,为什么顶级方法不能在这个对象上创建单例方法呢,
它本身
(并因此进入所有其他类,即名称空间污染比
通常是有意的)。这仍然允许顶级方法调用其他方法
顶级方法。如果顶级对象是由
一些
常量,那么这些方法可以从任何地方调用
具有
你真的想打字吗
到处都是“Main.print”?
在进一步的讨论中,他解释说,这是因为他觉得“假设是自然的”
hello
作为私有实例方法。问题是没有一个顶级函数实际添加到
,但直接向
Object
instance_methods
函数族始终表现为本征类仍然是原始类。也就是说,在类中定义的方法被视为直接在特征类中定义。例如:
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
主要的
不过,这是一个典型的特征类。将您的原始示例与此进行比较:
def self.hello; "hello world"; end
Object.instance_methods.include? :hello # => false
self.meta.instance_methods.include? :hello # => true
好的,但是如果我们真的想知道给定的函数是在本征类上定义的,而不是在原始类上定义的呢?
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