Ruby return语句不适用于super关键字?

Vol*_*ort 13 ruby

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)


ben*_*ado 8

super就像调用超类的方法实现的方法调用一样.在您的示例中,return关键字从任何其他方法调用返回Parent::test并继续执行Child::test.

  • @Omega尝试`return super`. (7认同)