Ruby 的 super 怎么用
2021/11/21 1:09:48
本文主要是介绍Ruby 的 super 怎么用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Ruby 的 super 仅用于继承中,用来给子方法调用父方法。
super 例子
class Parent def method(a, b) puts "#{a} - #{b}" end end class ChildA < Parent def method(a, b) super(b, a) end end class ChildB < Parent def method(a, b) super end end child_a = ChildA.new child_b = ChildB.new child_a.method('a', 'b') child_b.method('a', 'b')
输出结果
b - a a - b
super 解释
super 用于调用父类的方法,分为带参数和不带参数两种使用方法。
- 带参数:代表用指定的参数调用父方法
- 不带参数不带括号:代表将当前方法的参数,原封不动地传给父方法
不带参数调用时,不要写括号,写括号就变成带参数调用了,这是需要注意的点。
假设父方法是不定参数 *args
的方式,而如果子方法通过 super()
调用父方法,此时子方法的参数并没有传给父方法,这种将会出现隐秘的 bug。
这篇关于Ruby 的 super 怎么用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南
- 2024-09-26Springboot微服务资料入门教程