0
0
RubyHow-ToBeginner · 3 min read

How to Use Logical Operators in Ruby: Syntax and Examples

In Ruby, logical operators like and, or, and not combine or invert boolean expressions. You can also use &&, ||, and ! for the same purpose with different precedence rules.
📐

Syntax

Ruby provides two sets of logical operators: word-based (and, or, not) and symbol-based (&&, ||, !). The symbol-based operators have higher precedence, which affects how expressions are evaluated.

Operators:

  • and / &&: Logical AND
  • or / ||: Logical OR
  • not / !: Logical NOT (negation)
ruby
a = true
b = false

# Using symbol-based operators
result_and = a && b
result_or = a || b
result_not = !a

# Using word-based operators
result_and_word = a and b
result_or_word = a or b
result_not_word = not a
💻

Example

This example shows how to use logical operators to check multiple conditions and invert a boolean value.

ruby
is_raining = true
have_umbrella = false

if is_raining && have_umbrella
  puts "You can go outside."
elsif is_raining and not have_umbrella
  puts "Better stay inside."
else
  puts "Enjoy your day!"
end
Output
Better stay inside.
⚠️

Common Pitfalls

A common mistake is confusing the precedence of and/or with &&/||. The symbol-based operators (&&, ||) have higher precedence than assignment, while the word-based operators (and, or) have lower precedence, which can lead to unexpected results.

Example of wrong usage:

ruby
a = false
b = true

# Unexpected result because 'and' has lower precedence than '='
c = a and b
puts c  # Outputs false, not true

# Correct usage with parentheses or using '&&'
c = (a and b)
puts c  # Outputs false

c = a && b
puts c  # Outputs false
Output
false false false
📊

Quick Reference

OperatorMeaningExampleResult
&&Logical ANDtrue && falsefalse
andLogical AND (lower precedence)true and falsefalse
||Logical ORtrue || falsetrue
orLogical OR (lower precedence)true or falsetrue
!Logical NOT!truefalse
notLogical NOT (word form)not truefalse

Key Takeaways

Use &&, ||, and ! for logical operations with higher precedence.
and, or, and not are word-based operators with lower precedence and can affect assignment.
Always be careful with operator precedence to avoid unexpected results.
Use parentheses to clarify complex logical expressions.
Logical operators combine or invert boolean values to control program flow.