ruby: 在没有父对象的情况下调用 super class

ruby: calling super without having a parent class

我有一个 class 覆盖 self.new 并在其中调用 super,但是 class 不是从另一个 class 派生的。那么调用的具体内容是什么?

class Test
  attr_reader :blatt

  def self.new(blatt, quellformat, &block)
    begin
      # why can't I call initialize(blatt,quellformat) here? 
      # when I try this, it only prints "wrong # of arguments(2 for 1)"

      a = super(blatt, quellformat) # but this works...

      # some code
      a
    end
  end

  def initialize(blatt, quellformat)
    @name = blatt.blattname
    @datei = blatt.datei
    @blatt = blatt
    @qu = quellformat
  end
end

类 默认继承自 Object。因此,您的 super 调用将调用 Object.new.

why can't I call initialize(blatt,quellformat) here?

因为Test::new是一个class方法而Test#initialize是一个实例方法。您需要 class 的一个实例来调用 initialize.

but the class doesn't derive from another class

可能不明显,但你的 class 实际上是 Class.

的一个实例

So what exactly does the call?

通过定义 self.new,您将覆盖 Class#new。根据文档:

Calls allocate to create a new object of class’s class, then invokes that object’s initialize method, passing it args.

Ruby 实现如下所示:

def self.new(*args)
  obj = allocate
  obj.send(:initialize, *args)
  obj
end

调用 super 只是调用默认实现,即 Class#new,其作用相同。这是 C 代码:

VALUE
rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
{
    VALUE obj;

    obj = rb_obj_alloc(klass);
    rb_obj_call_init(obj, argc, argv);

    return obj;
}