|| Operator, return when result is known?
Asked Answered
A

5

12

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.

Anhwei answered 11/3, 2011 at 21:10 Comment(1)
Btw: You don't need the return in your method.Vogue
C
17

Ruby uses short-circuit evaluation.

This applies to both || and &&.

  • With || the right operand is not evaluated if the left operand is truthy.
  • With && the right operand is not evaluated if the left operand is falsy.
Cate answered 11/3, 2011 at 21:11 Comment(0)
V
6

|| 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.

Vogue answered 11/3, 2011 at 21:12 Comment(0)
B
2

|| 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

Bunkmate answered 11/3, 2011 at 21:14 Comment(0)
Y
0

As soon as one of the condition is true, the function will return.

Yachtsman answered 11/3, 2011 at 21:11 Comment(0)
C
0

You can test it yourself in irb, like this:

irb> p('Hello') || p('World')

As we know the function p prints its parameters(in an inspect 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 using puts instead of p, as puts always returns nil.

BTW, irb is a perfect place to play around ruby. You can test everything there, except a small portion of concurrency.

Corps answered 5/3, 2015 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.