簡體   English   中英

Ruby類方法繼承,如何阻止子方法執行?

[英]Ruby class method inheritance, how to stop the child method from executing?

這個問題與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

有誰知道如何實現我想要的輸出?

謝謝!

您可以使用簡單的if-end語句:

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

現在, B#test_method將返回false ,如果超級返回false 否則,它會評估if-end塊內的代碼。

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

這樣兩個都會運行,如果super是除了nilfalse之外的任何東西

或者,您可以使用更強的優先級&&但這個較低的優先級通常用作流控制。

請參閱Avdi的博客文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM