假设您正在使用不同的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_method
和UnboundMethod#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