[英]Ruby class method inheritance, how to stop the child method from executing?
This question pertains to a Ruby on Rails problem but this simplified problem will give me the solution I am looking for. 这个问题与Ruby on Rails问题有关,但这个简化的问题将为我提供我正在寻找的解决方案。
I have two classes, the child class is inheriting a parent method, but I want to half the execution of the child method code if certain conditions are met in the parent method. 我有两个类,子类继承父方法,但是如果在父方法中满足某些条件,我想要执行子方法代码的一半。
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
And the output is: 输出是:
method1
method2
My desired output is: 我想要的输出是:
method1
Does anyone know how to achieve my desired output? 有谁知道如何实现我想要的输出?
Thanks! 谢谢!
You could use simple if-end
statement: 您可以使用简单的
if-end
语句:
class B < A
def test_method
if super
puts 'method2'
end
end
end
Now, B#test_method
will return false
if super returns false
. 现在,
B#test_method
将返回false
,如果超级返回false
。 Otherwise it evaluates code inside if-end
block. 否则,它会评估
if-end
块内的代码。
class B < A
def test_method
super and puts 'method2'
end
end
This way both will run, if super is anything except nil
or false
这样两个都会运行,如果super是除了
nil
或false
之外的任何东西
Alternatively, you can use the stronger precedenced &&
but this lower precedence is often used as flow control. 或者,您可以使用更强的优先级
&&
但这个较低的优先级通常用作流控制。
See Avdi's blog post about this. 请参阅Avdi的博客文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.