怎么计算?是圆形的
更新:
(在irb)
Class.superclass = Module Module.class = Class
当Class是Module underclass时,怎么可能会说Module的类是Class?它是圆形,鸡肉和鸡蛋的东西.
对象:同样的问题:Object是对象模型中的根对象.它的类怎么可以是Class,因为Class对象甚至不存在?
解决方法
我们来看看MRI源代码的class.c文件:
void Init_class_hierarchy(void) { id_attached = rb_intern("__attached__"); rb_cBasicObject = boot_defclass("BasicObject",0); /* boot_defclass is defined as boot_defclass(const char *name,VALUE super) */ rb_cObject = boot_defclass("Object",rb_cBasicObject); rb_cModule = boot_defclass("Module",rb_cObject); rb_cClass = boot_defclass("Class",rb_cModule); /* Very important line: */ RBASIC(rb_cClass)->klass = RBASIC(rb_cModule)->klass = RBASIC(rb_cObject)->klass = RBASIC(rb_cBasicObject)->klass = rb_cClass; }
ruby.h中的这些定义也非常重要:
#define R_CAST(st) (struct st*) #define RBASIC(obj) (R_CAST(RBasic)(obj)) #define ROBJECT(obj) (R_CAST(RObject)(obj)) #define RCLASS(obj) (R_CAST(RClass)(obj)) #define RMODULE(obj) RCLASS(obj)
请注意,Object,Module和Class派生自BasicObject.确实,
irb(main):001:0> BasicObject.superclass => nil
这些对象被同时定义,并且它们都具有RBASIC(*) – > klass = rb_cClass.