Menu
Coddy logo textTech

Logical Operators Part 3

Part of the Fundamentals section of Coddy's Ruby journey — lesson 19 of 88.

Ruby also provides word-based alternatives for logical operators: and, or, and not. These work similarly to &&, ||, and !, but with one important difference: they have lower precedence.

true and false   # false (same as &&)
true or false    # true (same as ||)
not true         # false (same as !)

The lower precedence means these operators are evaluated after assignment. This can lead to unexpected behavior:

result = true && false   # result is false
result = true and false  # result is true!

In the second example, the assignment happens first (result = true), then and false is evaluated but its result is discarded. This is why most Ruby developers prefer &&, ||, and ! for conditions.

The word versions are typically reserved for control flow situations, which you'll encounter later. For now, stick with the symbol operators (&&, ||, !) when writing conditions to avoid surprises.

challenge icon

Challenge

Easy

You are provided with the following variables:

a = true
b = false
c = true

Use the word-based logical operators (and, or, not) to evaluate and display the following expressions, each on a separate line:

  1. a and b
  2. a or b
  3. not b
  4. a and c
  5. b or c
  6. not a

Each output should be either true or false.

Cheat sheet

Ruby provides word-based alternatives for logical operators: and, or, and not. These work similarly to &&, ||, and !, but with lower precedence.

true and false   # false
true or false    # true
not true         # false

The lower precedence means these operators are evaluated after assignment, which can lead to unexpected behavior:

result = true && false   # result is false
result = true and false  # result is true!

In the second example, the assignment happens first (result = true), then and false is evaluated but its result is discarded.

Most Ruby developers prefer &&, ||, and ! for conditions to avoid surprises. The word versions are typically reserved for control flow situations.

Try it yourself

# Variables are provided for you
a = true
b = false
c = true

# TODO: Write your code below
# Use the word-based logical operators (and, or, not) to evaluate and print each expression
# Each result should be printed on a separate line
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals