Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid short-circuit evaluation on

People also ask

What is short-circuit evaluation?

Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.

Which operators can be used to do a short-circuit evaluation?

The logical AND operator performs short-circuit evaluation: if the left-hand operand is false, the right-hand expression is not evaluated. The logical OR operator also performs short-circuit evaluation: if the left-hand operand is true, the right-hand expression is not evaluated.

What is short-circuit evaluation in the case of the and operator?

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first ...

Does short-circuit evaluation apply to conditions in loops?

Yes. Short circuit evaluation is not a property of if-condition or while-condition.


Try this:

([model1, model2].map(&:valid?)).all?

It'll return true if both are valid, and create the errors on both instances.


& works just fine.

irb(main):007:0> def a
irb(main):008:1> puts "a"
irb(main):009:1> false
irb(main):010:1> end
=> nil

irb(main):011:0> def b
irb(main):012:1> puts "b"
irb(main):013:1> true
irb(main):014:1> end
=> nil

irb(main):015:0> a && b
a
=> false

irb(main):016:0> a & b
a
b
=> false

irb(main):017:0> a and b
a
=> false

How about:

if [model1.valid?,model2.valid?].all?
  ...
end

Works for me.


Evaluate them separately and store the result in a variable. Then use a simple && between those booleans :)