在 Ruby 中让一个类继承 Proc

Nic*_*tia 3 ruby lambda inheritance proc

我一直在尝试继承ProcRuby中的类。我知道有很多其他方法可以实现我的类而无需实际继承Proc,但现在出于好奇我想知道。

我想要一个可以在没有作为参数传递的块的情况下实例化的类,但它就是行不通(似乎就是原因)。很明显,您无法在Proc没有块的情况下实例化实际对象(即使使用procor也不行lamba):

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
Run Code Online (Sandbox Code Playgroud)

我认为重写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
Run Code Online (Sandbox Code Playgroud)

有什么方法(从 Ruby 内部)可以绕过proc.c中的限制吗?或者有什么优雅的解决方法吗?

Jör*_*tag 5

super没有参数列表意味着“传递原始参数”。在本例中,原始参数是 string "hello",它被传递给Proc::new,但不需要参数!

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

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

m = MyClass.new "hello"
m.(23) # => 46
Run Code Online (Sandbox Code Playgroud)

显然,块不算作参数列表。你每天学习新的东西。