Ruby元类类层次结构

时间:2013-09-13 08:23:17

标签: ruby metaprogramming

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

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

它的内部类指针klass指向哪里? klassClass的情况下指向哪里,假设我们为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,这适用于所有元类。

1 个答案:

答案 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指向元类本身(图的那部分是正确的,但是指出了一些不一致的地方)。