这段代码中的超级是什么?
def initialize options = {}, &block
@filter = options.delete(:filter) || 1
super
end
Run Code Online (Sandbox Code Playgroud)
据我所知,这就像递归调用函数一样,对吧?
set*_*rgo 64
no ... super调用父类的方法(如果存在).另外,正如@EnabrenTane指出的那样,它也将所有参数传递给父类方法.
von*_*rad 55
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'
Run Code Online (Sandbox Code Playgroud)
您可以调用的次数没有限制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'
Run Code Online (Sandbox Code Playgroud)
但是,如果没有相同名称的父方法,Ruby会引发异常:
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’
Run Code Online (Sandbox Code Playgroud)
cvi*_*bha 21
该超级关键字可以用来调用同名的方法进行调用的类的超类.
它将所有参数传递给父类方法.
super和super()不一样
class Foo
def show
puts "Foo#show"
end
end
class Bar < Foo
def show(text)
super
puts text
end
end
Bar.new.show("Hello Ruby")
Run Code Online (Sandbox Code Playgroud)
子类中的super(没有括号)将使用与传递给原始方法的完全相同的参数调用父方法(因此Bar#show中的超级内容变为超级("Hello Ruby")并导致错误,因为父方法不接受任何参数)