2

这篇关于元类及其在 Ruby 对象模型中的位置的文章有一个类层次结构图。在其中,Class:Class(Class的单例类) 是其自身的一个实例,但我认为它应该是Class. 换句话说,如果我们有class_singletonclass如下对象:

class_singletonclass = Class.singleton_class
# => #<Class:Class>

它的内部类指针klass指向哪里?klass在 的情况下指向哪里Class,假设我们为 定义了一个类方法(单例方法)Class

我意识到Class已经定义了类方法。我想这Class很特别,并且在 MRI 中有自己的 C 实现,因此添加类方法将创建一个适当的元类。这个假设是错误的吗?

class.c在 MRI 中发现了以下内容:

/*!
 * 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这适用于所有元类。

4

1 回答 1

1

我已将inheritance上面链接的帖子中的扩展改编为 Ruby 2.0:

继承.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);
}

测试.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指向元类本身(图的那部分是正确的,但指向和 中的一些不一致)。

于 2013-09-13T09:24:48.983 回答