ruby 中super和super的区别

Python016

ruby 中super和super的区别,第1张

我们经常要在子类的initialize方法中调用super和super()。

从语法上说super和super()是有微妙区别的。

super不带括号表示调用父类的同名函数,并将本函数的所有参数传入父类的同名函数;

super()带括号则表示调用父类的同名函数,但是不传入任何参数;

演示代码如下:

1class SParent

2def initialize *args

3args.each {|arg| puts arg}

4end

5end

6

7class SChild <SParent

8def initialize a, b, c

9super

10end

11end

12

13a, b, c =*%W[a b c]

14SChild.new a, b, c # puts a, b, c if super

15SChild.new a, b, c # puts nothing if super()

可以看出当SChild的initialize中调用super()时,代码是不会打印任何信息的。这是因为super()没有向SParent的initialize方法传任何参数。

以下的两个类

object_a = A.new

那么怎么通过 object_a 来调用 B 类中的 a 这个method呢?

可以使用 super_method 这个方法来实现(因为A是继承B的)

如下:

object_a.method(:a).super_method.call #=>'b'