Ruby 中的 `super` 是什么?

What is `super` in Ruby?

在 rails 上浏览关于 ruby 的互联网时,我看到 super 这个词。谁能告诉我它是什么以及它能做什么?

super 方法调用父 class 方法。

例如:

class A
  def a
    # do stuff for A
  end
end

class B < A
  def a
    # do some stuff specific to B
    super
    # or use super() if you don't want super to pass on any args that method a might have had
    # super/super() can also be called first
    # it should be noted that some design patterns call for avoiding this construct
    # as it creates a tight coupling between the classes.  If you control both
    # classes, it's not as big a deal, but if the superclass is outside your control
    # it could change, w/o you knowing.  This is pretty much composition vs inheritance
  end
end

如果还不够可以继续学习here

当您使用继承时,如果您想从子 class 调用父 class 方法,我们使用 super

c2.1.6 :001 > class Parent
2.1.6 :002?>   def test
2.1.6 :003?>     puts "am in parent class"
2.1.6 :004?>   end
2.1.6 :005?>  end
 => :test_parent 
2.1.6 :006 > 
2.1.6 :007 >   class Child < Parent
2.1.6 :008?>     def test
2.1.6 :009?>       super
2.1.6 :010?>     end
2.1.6 :011?>   end
 => :test_parent 
2.1.6 :012 > Child.new.test
am in parent class
 => nil 
2.1.6 :013 > 

我们可以通过不同的方式使用 super(例如:super、super())。

它被用来实现超class当前方法的实现。 在方法体内,对 super 的调用就像对原始方法的调用一样。并且 方法体的搜索从被发现包含原始方法的对象的 superclass 开始。

def url=(addr)
super (addr.blank? || addr.starts_with?('http')) ? addr : http://#{addr}
end

Ruby使用super关键字调用当前方法的超类实现。 在方法体内,对 super 的调用就像对原始方法的调用一样。 方法体的搜索从被发现包含原始方法的对象的超类开始。

def url=(addr)
  super (addr.blank? || addr.starts_with?('http')) ? addr : http://#{addr}
end