Logical Operators – and (&&), or (||), and not (!) in Ruby

Logical Operators – and (&&), or (||), and not (!) in Ruby

Logical operators are used to form more complex criteria that test more than one condition for an if expression. Today in this article we will discuss the logical operators used in Ruby language.

Ruby has three logical operators: and (&&), or (||), and not (!). Ruby can use words instead of the logical operator symbols (and, or, not), but those have lower precedence and are generally avoided.


Table of Contents

and (&&)

A conditional using and evaluates as true if, and only if, all of its operands are true. Otherwise, the entire conditional evaluates to false.
For example:

or (||)

The or (||) operator evaluates to true if either (or all) of its operands are true, and false if all operands are false.
For example:

not (!)

The not (!) operator reverses the state of a single operand. The result of not true is false, and not false is true.
For example:

You can chain together multiple conditions with the logical operators to check for multiple conditions. Parentheses can be used to group together separate conditions for clarity and to control the order of operations.
For example:

Leave a Reply