假设您正在使用不同的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
Run Code Online (Sandbox Code Playgroud)
有没有办法super在这里获得在线的arity ?
(真实的用例:我正在调用super知道超类不带任何参数.但是,如果超类实现(在gem中)发生变化,我想发出警告.)
谢谢你的帮助!
关于你的真实用例:没有必要自己检查论点.打电话吧
super(arg1)
Run Code Online (Sandbox Code Playgroud)
ArgumentError如果参数计数不匹配,Ruby将引发一个.
由于一些downvotes,我想我应该回答你的初步问题.
如何获得"超级"的智慧?
使用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
Run Code Online (Sandbox Code Playgroud)
从内部B#foo,你可以写:
class B < A
def foo(arg1, arg2)
method(__method__).super_method.arity #=> 1
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
442 次 |
| 最近记录: |