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

时间:2018-02-04 15:27:41

标签: ruby metaprogramming

您好我在这里对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中定义的?

谢谢。

1 个答案:

答案 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的其他用法相同。