您好我在这里对Ruby的对象模型感到困惑:
class Module
# `hello` should be readily available within all regular classes
def hello
'Hello World'
end
end
# `special` should be available within all regular singleton classes
class Module
class << self
def special
puts 'This is the special method defined in Module.singleton_class'
end
end
end
class MyClass
hello # => 'Hello World'
# special # this correctly raises an error here
# special should only available in MyClass.singleton_class and it actually is.
# However `hello` method shouldn't be available in `MyClass.singleton_class` (only in MyClass) but yet it is. Why?
class << self
special # This only works here as it should
hello # but strangely this works too! It shouldn't though...
end
end
您能否向我解释为什么方法hello
可以在MyClass.singleton_class
中使用,因为它是在Module
而不是Module.singleton_class
中定义的?
谢谢。
答案 0 :(得分:2)
原因如下:
class MyClass
class << self
hello # but strangely this works too! It shouldn't though...
self.class.ancestors # => [Class, Module, Object, Kernel, BasicObject]
end
end
self
有一个Class
,它是您在方法Module
中修补的hello
,因此它可以像任何其他继承的方法一样使用。
与hello
的其他用法相同。