这个问题与 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
现在,如果 super 返回 false
,B#test_method
将返回 false
。否则它会评估 if-end
block 内的代码。
关于Ruby类方法继承,如何让子方法停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459098/