【发布时间】:2018-09-26 18:40:25
【问题描述】:
我正在阅读 another question 和 answer,其中提到使用 Module#const_get 实例方法在模块中查找类。例如:
module M
class C
end
end
p M.const_get 'C'
#=> M::C
我对@987654325@的方法很好奇所以我用ri发现:
ri Module#const_get
...
This method will recursively look up constant names if a namespaced
class name is provided. For example:
module Foo; class Bar; end end
Object.const_get 'Foo::Bar'
...
似乎Object::const_get 是一个单例方法。在我们的上下文中使用它是有效的:
module M
class C
end
end
p Object.const_get 'M::C'
#=> M::C
但是没有任何关于该单例方法的记录:
ri Object::const_get
Nothing known about Object::const_get
ri Object.const_get
Nothing known about Object.const_get
这让我很困惑,因为我知道 Module 是 Object,但 Object 不是 Module:
Module.ancestors
#=> [Module, Object, Kernel, BasicObject]
Object.ancestors
#=> [Object, Kernel, BasicObject]
除了然后我使用Object#is_a? 实例方法检查并发现我错了:
Module.is_a? Object
#=> true
Object.is_a? Module
#=> true
最初是一个无辜的ri 查询,让我对整个 Ruby 对象模型感到困惑。
- 如果
Module不在Object的祖先链中,为什么Object.is_a? Module #=> true? -
Object是如何知道const_get方法的?
【问题讨论】:
标签: ruby