Ruby类方法继承,如何阻止子方法执行?

时间:2013-07-03 22:26:01

标签: ruby ruby-on-rails-3 oop

这个问题与Ruby on Rails问题有关,但这个简化的问题将为我提供我正在寻找的解决方案。

我有两个类,子类继承父方法,但是如果在父方法中满足某些条件,我想要执行子方法代码的一半。

class A

  def test_method
    puts 'method1'
    return false
  end

end

class B < A

  def test_method
    super
    #return false was called in parent method, I want code to stop executing here
    puts 'method2'
  end

end

b = B.new
b.test_method

输出是:

method1
method2

我想要的输出是:

method1

有谁知道如何实现我想要的输出?

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用简单的if-end声明:

class B < A
  def test_method
    if super
      puts 'method2'
    end
  end
end

现在,如果超级回复B#test_methodfalse将返回false。否则,它会评估if-end块内的代码。

答案 1 :(得分:3)

class B < A
  def test_method
    super and puts 'method2'
  end
end

这样两种方式都可以运行,如果超级是nilfalse

以外的任何内容

或者,您可以使用更强的优先级&&,但这个较低的优先级通常用作流控制。

请参阅Avdi's blog post