Java教程

Ruby 的 super 怎么用

本文主要是介绍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 怎么用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!