ruby - 在 Ruby 中让一个类继承 Proc

标签 ruby inheritance lambda proc

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

我想要一个可以在没有 block 作为参数传递的情况下实例化的类,但它就是行不通( this 似乎就是原因)。很明显,您无法在没有 block 的情况下实例化实际的 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 表示“传递原始参数”。在本例中,原始参数是字符串 "hello",它被传递给 Proc::new,但不需要参数!

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

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

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

显然, block 不算作参数列表。您每天都会学到新东西。

关于ruby - 在 Ruby 中让一个类继承 Proc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364402/

相关文章:

ruby-on-rails - 中间人新文章.slim失败

ruby - 从图像中提取或分析视觉信息

Ruby 日期解析

java - 扩展一个包含对自身列表的引用的类

Python 类继承 : How to initialize a subclass with values not in the parent class

ruby - 安装可移植 ruby​​ 和可移植 xampp 以便在我的 Windows 机器 : Is that possible? 中使用 compass 和 sass

java - 当父类(super class)型方法调用同时存在于父类(super class)型和子类型中的方法时,调用哪个实例方法

amazon-web-services - 无法删除AWS Lambda @ Edge副本

c# - 将 Expression<Func<T, U>> 转换为 Expression<Func<object, object>>

mysql - 如何使用nodeJs在Lambda函数中使用mysq事务提交回滚