Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

|| Operator, return when result is known?

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.

like image 686
Gunner Avatar asked Mar 11 '11 21:03

Gunner


People also ask

What does the || operator do in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values.

Is || and && the same?

&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true. so it continues till the end to check atleast one condition to become true.

What is && and || called?

&& and || are called short circuit operators. When they are used, for || - if the first operand evaluates to true , then the rest of the operands are not evaluated. For && - if the first operand evaluates to false , the rest of them don't get evaluated at all.

What does || mean in C#?

The conditional logical OR operator || , also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true . Otherwise, the result is false . If x evaluates to true , y is not evaluated.


1 Answers

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.
like image 179
Mark Byers Avatar answered Oct 12 '22 11:10

Mark Byers