Skip to content

Instantly share code, notes, and snippets.

@mehdi-farsi
Last active March 18, 2018 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdi-farsi/172c2b85ddba8e766cac2744058e2f55 to your computer and use it in GitHub Desktop.
Save mehdi-farsi/172c2b85ddba8e766cac2744058e2f55 to your computer and use it in GitHub Desktop.
Avoid Short-Circuit Evaluation During OR/AND Expression

Short-circuit evaluation

By default, the || and && operators use the Short-circuit evaluation principle

irb> true || puts('short-circuit evaluation')
 => true 
irb> false && puts('short-circuit evaluation')
=> false

For both statements the left side of the expression suffices to determine the value of the expression. So, the puts('short-circuit evaluation') is never evaluated.

The | and & operators

Sometimes, you need to evaluate the whole expression. To do so, you can use the | and & operators. They are both methods of the TrueClass and FalseClass classes

irb> false & puts('avoid short-circuit evaluation')
avoid short-circuit evaluation
 => false
irb> true | puts('avoid short-circuit evaluation')
avoid short-circuit evaluation
 => true 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment