ruby – 如何获得“超级”的智慧?

假设您正在使用不同的arity覆盖子类中的方法
class A
  def foo(arg)          # arity is 1
    # doing something here
  end
end

class B < A
  def foo(arg1,arg2)   # arity is 2
    super(arg1)         # <- HERE
  end
end

有没有办法在这里获得超级的优势?

(真实用例:我正在调用超级知道超类不接受任何参数.但是,如果超类实现(在gem中)发生变化,我想发出警告.)

谢谢你的帮助!

解决方法

关于你的真实用例:没有必要自己检查参数.打电话吧
super(arg1)

如果参数计数不匹配,Ruby将引发ArgumentError.

更新

由于一些downVotes,我想我应该回答你的初步问题.

How to get the arity of “super”?

从Ruby 2.2开始,有Method#super_methodUnboundMethod#super_method

class A
  def foo(arg)
  end
end

class B < A
  def foo(arg1,arg2)
  end
end

B.instance_method(:foo).arity #=> 2
B.instance_method(:foo).super_method.arity #=> 1

从B#foo中,你可以写:

class B < A
  def foo(arg1,arg2)
    method(__method__).super_method.arity #=> 1
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...