如何避免短路评估
我正在使用 Ruby on Rails 并希望验证两种不同的模型:
if (model1.valid? && model2.valid?)
...
end
但是,“&&” 运算符使用短路评估(即,仅当“model1.valid?”为真时才评估“model2.valid?”),这会阻止在 model1 无效时执行 model2.valids。
有没有相当于“&&”的 哪个不会使用短路评估? 我需要评估这两个表达式。
I'm working with Ruby on Rails and would like to validate two different models :
if (model1.valid? && model2.valid?)
...
end
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
试试这个:
如果两者都有效,它将返回 true,并在两个实例上创建错误。
Try this:
It'll return true if both are valid, and create the errors on both instances.
& 工作得很好。
& works just fine.
怎么样:
对我有用。
How about:
Works for me.
分别评估它们并将结果存储在变量中。 然后使用简单的 && 在这些布尔值之间:)
Evaluate them separately and store the result in a variable. Then use a simple && between those booleans :)
使代码片段对未来开发人员更易于维护的关键概念之一是其表现力。
让我们考虑以下示例:
或者
他们都做得很好,但是当未来的开发人员遇到其中任何一个而没有看到任何解释性注释、您意图的文档,或者没有直接联系您时,该开发人员将在不知道的情况下修改它们目的是为了避免短路评估。
如果没有测试,情况会变得更糟。
这就是为什么我建议引入一个小的包装方法,它可以让所有事情立即变得清晰。
然后在你的代码库的某个地方。
One of the key concepts which allow making a code snippet more maintainable for a future developer is its expressiveness.
Let's consider the following examples:
or
Both of them do their job well, but when a future developer will encounter any of them without seeing any explanatory comments, docs of your intent, or without reaching you directly, this developer will modify them having no idea that the purpose was to avoid the short-circuit evaluation.
Things become even worse when you have no tests.
This is why I suggest introducing a small wrapper method which will make all things clear immediately.
And later somewhere in your codebase.
我遇到了类似的问题,我需要检查两个字符串是否不为空。 短路阻止了我检查两个字符串,但我发现在 ruby 中我们可以使用 if not 或除非
或
I had a similar issue where I needed to check if two string weren't blank. Short circuit was preventing me to check both strings but I found out that in ruby we can use if not or unless
or
您可以将一个块传递给
all?
,而不是使用 map 创建额外的数组。Instead of creating an extra array with map, you can pass a block to
all?
.