如何避免短路评估 [英] How to avoid short-circuit evaluation on
本文介绍了如何避免短路评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Ruby on Rails,并想验证两个不同的模型:
I'm working with Ruby on Rails and would like to validate two different models :
if (model1.valid? && model2.valid?)
...
end
但是,&&"操作员使用短路评估(即,只有在"model1.valid?"为true时才评估"model2.valid?"),这可以防止在model1无效的情况下执行model2.valids.
However, "&&" operator uses short-circuit evaluation (i.e. it evaluates "model2.valid?" only if "model1.valid?" is true), which prevents model2.valids to be executed if model1 is not valid.
是否有等同于&&"哪个不会使用短路评估?我需要对两个表达式进行求值.
Is there an equivalent of "&&" which would not use short-circuit evaluation? I need the two expressions to be evaluated.
推荐答案
尝试一下:
([model1, model2].map(&:valid?)).all?
如果两个都有效,它将返回true,并在两个实例上创建错误.
It'll return true if both are valid, and create the errors on both instances.
这篇关于如何避免短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文