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

前端之家收集整理的这篇文章主要介绍了ruby – 如何获得“超级”的智慧?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设您正在使用不同的arity覆盖子类中的方法
  1. class A
  2. def foo(arg) # arity is 1
  3. # doing something here
  4. end
  5. end
  6.  
  7. class B < A
  8. def foo(arg1,arg2) # arity is 2
  9. super(arg1) # <- HERE
  10. end
  11. end

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

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

谢谢你的帮助!

解决方法

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

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

更新

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

How to get the arity of “super”?

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

  1. class A
  2. def foo(arg)
  3. end
  4. end
  5.  
  6. class B < A
  7. def foo(arg1,arg2)
  8. end
  9. end
  10.  
  11. B.instance_method(:foo).arity #=> 2
  12. B.instance_method(:foo).super_method.arity #=> 1

从B#foo中,你可以写:

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

猜你在找的Ruby相关文章