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
I though that, since the test
method from the Parent
class immediately uses the return statement, it should not be possible to print the line of the Child
class. But it is indeed printed. Why is that?
我虽然如此,因为来自Parent类的测试方法立即使用return语句,所以不应该打印Child类的行。但确实是印刷品。这是为什么?
Ruby 1.8.7, Mac OSX.
Ruby 1.8.7,Mac OSX。
2 个解决方案
#1
8
super
acts like a method call that calls the superclass's method implementation. In your example, the return
keyword returns from Parent::test
and continues executing Child::test
, just like any other method call would.
super就像调用超类的方法实现的方法调用一样。在您的示例中,return关键字从Parent :: test返回并继续执行Child :: test,就像任何其他方法调用一样。
#2
11
Another way to think of the call to super
in this context is if it were any other method:
在这种情况下考虑超级调用的另一种方法是它是否是任何其他方法:
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!"
If you really wanted to prevent the call to p
, you need to use the return value from super
in a conditional:
如果你真的想阻止对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
#1
8
super
acts like a method call that calls the superclass's method implementation. In your example, the return
keyword returns from Parent::test
and continues executing Child::test
, just like any other method call would.
super就像调用超类的方法实现的方法调用一样。在您的示例中,return关键字从Parent :: test返回并继续执行Child :: test,就像任何其他方法调用一样。
#2
11
Another way to think of the call to super
in this context is if it were any other method:
在这种情况下考虑超级调用的另一种方法是它是否是任何其他方法:
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!"
If you really wanted to prevent the call to p
, you need to use the return value from super
in a conditional:
如果你真的想阻止对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