||运算符,当结果已知时返回?
我有一个类似于以下的函数:
def check
return 2 == 2 || 3 != 2 || 4 != 5
end
我的问题是,即使第一个为 true,Ruby 也会执行所有比较,因此该函数返回 true。我的检查更加密集,所以我想知道是否应该以不同的方式解决这个问题,以避免每次都进行所有检查。
irb(main):004:0> 2 == 2 || 3 != 2 || 4 != 5
=> true
谢谢。
I have a function similar to the following:
def check
return 2 == 2 || 3 != 2 || 4 != 5
end
My question is, will Ruby perform all the comparisons even though the first is true, and thus the function return true. My checks are much more intensive, so I'd like to know if I should break this out in a different way to avoid making all the checks every time.
irb(main):004:0> 2 == 2 || 3 != 2 || 4 != 5
=> true
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Ruby 使用短路评估。
这适用于 ||和&&。
||
,如果左操作数为真,则不会计算右操作数。&&
,如果左操作数为假,则不会计算右操作数。Ruby uses short-circuit evaluation.
This applies to both || and &&.
||
the right operand is not evaluated if the left operand is truthy.&&
the right operand is not evaluated if the left operand is falsy.一旦第一个条件为真,
||
就会短路。所以是的,如果你把最昂贵的条件放在最后会有帮助。||
short-circuits as soon as the first condition is true. So yes, it will help if you put the most expensive conditions at the end.||默认情况下会短路求值,这意味着一旦遇到第一个“true”表达式,它将停止求值(除非您明确声明希望使用“or”运算符对所有表达式求值)。
参考:
http://en.wikipedia.org/wiki/Short- Circuit_evaluation
|| will by default short-circuit evaluate, meaning that once the first "true" expression is encountered it will stop evaluation (unless you explicitly state you want all expressions to evaluate with the 'or' operator).
reference:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
一旦其中一个条件为真,该函数就会返回。
As soon as one of the condition is true, the function will return.
您可以在 irb 中自己测试它,如下所示:
正如我们所知,函数
p
打印其参数(以inspect
方式)然后返回它们,因此如果||
短路,仅打印"Hello"
,否则同时打印"Hello"
和"World"
。您还可以使用
puts
而不是p
来测试逻辑&&
运算符,因为puts
始终如此返回nil
。顺便说一句,irb 是玩 ruby 的完美场所。您可以在那里测试所有内容,除了一小部分并发性。
You can test it yourself in irb, like this:
As we know the function
p
prints its parameters(in aninspect
manner) then returns them, so if the||
short circuits, only"Hello"
is printed, otherwise both"Hello"
and"World"
are printed.You can also test the logical
&&
operator, by usingputs
instead ofp
, asputs
always returnsnil
.BTW, irb is a perfect place to play around ruby. You can test everything there, except a small portion of concurrency.