超级Ruby类

时间:2014-08-07 18:46:35

标签: ruby

我知道'super'调用父类的方法。这是jekyll项目的代码:

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

这是一个类声明:

class Post

没有父类。在这种背景下,什么是“超级”?

这是full class code

3 个答案:

答案 0 :(得分:5)

super不仅调用父类的方法,还调用包含模块中的方法。

一般的解决方案顺序是

  • 对象的本征类(或单一类,它是同一事物的替代名称)的实例方法
  • 对象的实例方法
  • 任何包含模块中的方法,从最后一个包含的模块开始
  • 如果尚未找到,请执行父类的所有先前步骤(然后直到找到方法)

在这种情况下,它是Convertible#read_yaml

答案 1 :(得分:3)

包含模块会将其添加为类的祖先,允许使用super调用其方法。 Post包括ComparableConvertible,因此超级方法属于其中一个类。

例如:

module Foo; end
class Bar
  include Foo
end

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

答案 2 :(得分:-3)

在Ruby中, super 关键字使用相同的参数调用同名的父方法。

它也可以用于继承的类。

示例

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可以被调用任意次,并且可以在多个继承的类中使用。

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'

如果没有相同名称的父方法,则会引发异常。

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’

希望这会有所帮助。