Ruby 的 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 用于调用父类的方法,分为带参数和不带参数两种使用方法。
不带参数调用时,不要写括号,写括号就变成带参数调用了,这是需要注意的点。
假设父方法是不定参数 *args
的方式,而如果子方法通过 super()
调用父方法,此时子方法的参数并没有传给父方法,这种将会出现隐秘的 bug。