简体   繁体   English

Ruby类中的super

[英]super in the Ruby class

As I know 'super' calls the method of parent class. 据我所知,“ super”调用父类的方法。 Here is a code from jekyll project: 这是jekyll项目的代码:

def read_yaml(base, name)
  super(base, name)
  self.extracted_excerpt = extract_excerpt
end

And here is a class declaration: 这是一个类声明:

class Post

There is no parent class. 没有父类。 What is the 'super' on this context ? 在这种情况下,什么是“超级”?

Here is full class code . 这是完整的类代码

super doesn't just call methods on the parent class but also those in included modules. super不仅会在父类上调用方法,还会在包含的模块中调用方法。

The general resolution order is 一般解决顺序是

  • instance methods of the eigenclass (or singleton class, which is an alternative name for the same thing) of the object 对象的本征类(或单例类,是同一事物的替代名称)的实例方法
  • instance methods of the object 对象的实例方法
  • methods in any included modules, starting from the last included module 任何包含的模块中的方法,从最后一个包含的模块开始
  • if not yet found, do all previous steps for the parent class (and then up until a method is found) 如果尚未找到,请对父类执行所有之前的步骤(然后直到找到方法)

In this case, its Convertible#read_yaml . 在这种情况下,其Convertible#read_yaml

Including a module adds it as an ancestor of the class, allowing its methods to be called with super . 包含模块会将其添加为该类的祖先,从而允许使用super调用其方法。 Post includes both Comparable and Convertible , so the super method is in one of those classes. Post包含ComparableConvertible ,因此super方法在这些类之一中。

For example: 例如:

module Foo; end
class Bar
  include Foo
end

Bar.ancestors
# [Bar, Foo, Object, Kernel, BasicObject]

In Ruby, the super keyword calls a parent method of the same name using the same arguments. 在Ruby中, super关键字使用相同的参数调用相同名称的父方法。

It can also be used for inherited classes. 它也可以用于继承的类。

Example

class Foo
  def baz(str)
    p 'parent with ' + str
  end
end
class Bar < Foo
  def baz(str)
    super
    p 'child with ' + str
  end
end

Bar.new.baz('test') # => 'parent with test' \ 'child with test'

Super can be called any number of times and can be used in multiple inherited classes. Super可以被调用任意次,并且可以在多个继承的类中使用。

class Foo
  def gazonk(str)
    p 'parent with ' + str
  end
end

class Bar < Foo
  def gazonk(str)
    super
    p 'child with ' + str
  end
end

class Baz < Bar
  def gazonk(str)
    super
    p 'grandchild with ' + str
  end
end

Baz.new.gazonk('test') # => 'parent with test' \ 'child with test' \ 'grandchild with test'

An exception will be raised if there is no parent method of the same name. 如果没有同名的父方法 ,将引发异常。

class Foo; end

class Bar < Foo
  def baz(str)
    super
    p 'child with ' + str
  end
end

Bar.new.baz('test') # => NoMethodError: super: no superclass method ‘baz’

Hope this helped. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM