Menu
Coddy logo textTech

Logical Operators Part 4

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

When you combine multiple logical operators in a single expression, Ruby evaluates them in a specific order based on operator precedence. Understanding this order helps you write correct conditions and avoid unexpected results.

The precedence from highest to lowest is: ! (not), then && (and), then || (or). This means ! is evaluated first, followed by &&, and finally ||:

true || false && false   # true (&&  evaluates first)
# Same as: true || (false && false)

!false && true           # true (! evaluates first)
# Same as: (!false) && true

You can use parentheses to override the default precedence and make your intentions clear:

(true || false) && false  # false (parentheses force || first)
true || (false && false)  # true (default behavior)

Even when parentheses aren't strictly necessary, adding them often makes complex expressions easier to read. When in doubt, use parentheses to explicitly show how conditions should be grouped.

challenge icon

Challenge

Easy

You are provided with the following variables:

x = true
y = false
z = true
a = false

Evaluate the following expressions and display each result on a separate line. Pay attention to operator precedence: ! is evaluated first, then &&, and finally ||.

  1. x || y && z
  2. !y && z
  3. x && y || z
  4. !a || y && z
  5. x && !y && z
  6. (x || y) && a
  7. x || (y && a)
  8. !(x && y) || z

Each output should be either true or false.

Cheat sheet

Ruby evaluates logical operators in a specific order based on operator precedence:

  1. ! (not) - highest precedence
  2. && (and) - medium precedence
  3. || (or) - lowest precedence

Examples of operator precedence:

true || false && false   # true (&&  evaluates first)
# Same as: true || (false && false)

!false && true           # true (! evaluates first)
# Same as: (!false) && true

Use parentheses to override default precedence or improve readability:

(true || false) && false  # false (parentheses force || first)
true || (false && false)  # true (default behavior)

Try it yourself

# Variables are already defined for you
x = true
y = false
z = true
a = false

# TODO: Evaluate each expression and print the result on a separate line
# Remember operator precedence: ! first, then &&, then ||

# 1. x || y && z
puts # your expression here

# 2. !y && z
puts # your expression here

# 3. x && y || z
puts # your expression here

# 4. !a || y && z
puts # your expression here

# 5. x && !y && z
puts # your expression here

# 6. (x || y) && a
puts # your expression here

# 7. x || (y && a)
puts # your expression here

# 8. !(x && y) || z
puts # your expression here
quiz iconTest yourself

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

All lessons in Fundamentals