在 Ruby 中有一个 class 继承 Proc

Have a class inherit Proc in Ruby

我一直在尝试继承Ruby中的Procclass。我知道有很多其他方法可以在不实际继承 Proc 的情况下实现我的 class,但现在我出于好奇想知道。

我想要一个 class 可以在没有块作为参数传递的情况下实例化,但它就是行不通(this 似乎是原因)。很明显,你不能在没有块的情况下实例化实际的 Proc(即使使用 proclamba):

Proc.new proc {|x| 2 * x } # => ArgumentError: tried to create Proc object without a block
Proc.new lambda {|x| 2 * x } # => ArgumentError: tried to create Proc object without a block

我假设重写 initialize 可能就可以解决问题,但实际上即使重写 new 也行不通:

class MyClass < Proc
  def new *args, &block
    super { |x| 2 * x }
  end

  def initialize *args, &block
    super { |x| 2 * x }    
  end
end

MyClass.new { |x| 2 * x } # => everything is fine
MyClass.new "hello" # => ArgumentError: tried to create Proc object without a block

是否有任何方法(从 Ruby 中)绕过 proc.c 中的限制?或者任何优雅的解决方法?

super 没有参数列表意味着 "pass the original arguments along"。在这种情况下,原始参数是字符串 "hello",它被传递给 Proc::new,但它没有参数!

解决方法是显式不传递任何参数:

class MyClass < Proc
  def self.new(*)
    super() {|x| 2 * x }
  end
end

m = MyClass.new "hello"
m.(23) # => 46

显然,块不算作参数列表。你每天都能学到新东西。