ruby – 如何获得“超级”的智慧?
发布时间:2020-12-16 21:10:25 所属栏目:百科 来源:网络整理
导读:假设您正在使用不同的arity覆盖子类中的方法: class A def foo(arg) # arity is 1 # doing something here endendclass B A def foo(arg1,arg2) # arity is 2 super(arg1) # - HERE endend 有没有办法在这里获得超级的优势? (真实用例:我正在调用超级知道
假设您正在使用不同的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,我想我应该回答你的初步问题.
从Ruby 2.2开始,有 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |