class Parent
def test
return
end
end
class Child < Parent
def test
super
p "HOW IS THIS POSSIBLE?!"
end
end
c = Child.new
c.test
Run Code Online (Sandbox Code Playgroud)
我虽然如此,因为类中的test
方法Parent
立即使用return语句,所以不应该打印Child
类的行.但它确实印刷了.这是为什么?
Ruby 1.8.7,Mac OSX.
Cad*_*ade 12
super
在这种情况下考虑调用的另一种方法是它是否是任何其他方法:
class Parent
def foo
return
end
end
class Child < Parent
def test
foo
p "THIS SEEMS TOTALLY REASONABLE!"
end
end
c = Child.new
c.test
# => "THIS SEEMS TOTALLY REASONABLE!"
Run Code Online (Sandbox Code Playgroud)
如果你真的想阻止调用p
,你需要super
在条件中使用返回值:
class Parent
def test
return
end
end
class Child < Parent
def test
p "THIS SEEMS TOTALLY REASONABLE!" if super
end
end
c = Child.new
c.test
# => nil
Run Code Online (Sandbox Code Playgroud)
super
就像调用超类的方法实现的方法调用一样.在您的示例中,return
关键字从任何其他方法调用返回Parent::test
并继续执行Child::test
.