Module.singleton_class 中定义的方法的可用性

Availability of methods defined in Module.singleton_class

嗨,我对 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

你能解释一下为什么方法 helloMyClass.singleton_class 中可用,因为它是在 Module 而不是 Module.singleton_class 中定义的吗?

谢谢。

原因如下:

  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,它是您在方法 hello 中修补到的 Module,因此它可以像任何其他继承方法一样使用.

hello 的其他用法相同。