【问题标题】:Ruby class method inheritance, how to stop the child method from executing?Ruby类方法继承,如何阻止子方法执行?
【发布时间】:2013-07-03 22:26:01
【问题描述】:

这个问题与 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

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

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

    现在,如果 super 返回 falseB#test_method 将返回 false。否则,它会评估 if-end 块内的代码。

    【讨论】:

    • 谢谢。看到答案就简单多了!
    【解决方案2】:
    class B < A
      def test_method
        super and puts 'method2'
      end
    end
    

    如果 super 是除nilfalse 之外的任何东西,那么两者都会运行

    或者,您可以使用优先级更高的&amp;&amp;,但这种较低的优先级通常用作流量控制。

    请参阅Avdi's blog post 了解此内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      相关资源
      最近更新 更多