This post关于元类及其在Ruby对象模型中的位置有一个类层次结构图。在其中,Class:Class
(Class
的单例类)是其自身的实例,但我认为它应该是Class
的实例。换句话说,如果我们有对象class_singletonclass
如下:
class_singletonclass = Class.singleton_class
# => #<Class:Class>
它的内部类指针klass
指向哪里? klass
在Class
的情况下指向哪里,假设我们为Class
定义了一个类方法(单例方法)?
我意识到Class
已经定义了类方法。我想Class
是特殊的,并且在MRI中有自己的C实现,所以添加类方法会创建一个合适的元类。这个假设是错的吗?
我在MRI class.c
中找到了以下内容:
/*!
* A utility function that wraps class_alloc.
*
* allocates a class and initializes safely.
* \param super a class from which the new class derives.
* \return a class object.
* \pre \a super must be a class.
* \post the metaclass of the new class is Class.
*/
VALUE
rb_class_boot(VALUE super)
{
VALUE klass = class_alloc(T_CLASS, rb_cClass);
RCLASS_SET_SUPER(klass, super);
RCLASS_M_TBL(klass) = st_init_numtable();
OBJ_INFECT(klass, super);
return (VALUE)klass;
}
行\post the metaclass of the new class is Class.
表明Class
的元类确实是Class
,这适用于所有元类。
答案 0 :(得分:1)
我已将上面链接的帖子inheritance
扩展到Ruby 2.0:
<强> inheritance.c 强>
#include "ruby.h"
VALUE real_super(VALUE self)
{
return RCLASS_SUPER(RBASIC(self)->klass);
}
VALUE real_klass(VALUE self)
{
return RBASIC(self)->klass;
}
void Init_inheritance()
{
rb_define_method(rb_cClass,"real_super",real_super,0);
rb_define_method(rb_cClass,"real_klass",real_klass,0);
}
<强> test.rb 强>
require_relative 'inheritance'
puts "Object real class: #{Object.real_klass}"
puts "Object real superclass: #{Object.real_super}"
puts "Class real class: #{Class.real_klass}"
puts "Class real superclass: #{Class.real_super}"
puts "Class metaclass real class: #{Class.singleton_class.real_klass}"
puts "Class metaclass real superclass: #{Class.singleton_class.real_super}"
puts "Object metaclass real class: #{Object.singleton_class.real_klass}"
puts "Object metaclass real superclass: #{Object.singleton_class.real_super}"
puts "An object singleton class real class: #{Object.new.singleton_class.real_klass}"
puts "An object singleton class real superclass: #{Object.new.singleton_class.real_super}"
输出为:
Object real class: #<Class:Object>
Object real superclass: #<Class:BasicObject>
Class real class: #<Class:Class>
Class real superclass: #<Class:Module>
Class metaclass real class: #<Class:#<Class:Class>>
Class metaclass real superclass: #<Class:#<Class:Module>>
Object metaclass real class: #<Class:#<Class:Object>>
Object metaclass real superclass: #<Class:#<Class:BasicObject>>
An object singleton class real class: #<Class:Object>
An object singleton class real superclass: #<Class:BasicObject>
因此,在元类的情况下,klass
指向元类本身(图的那部分是正确的,但是指出了一些不一致的地方)。