0
0
Rubyprogramming~5 mins

Logical operators (&&, ||, !) in Ruby

Choose your learning style9 modes available
Introduction

Logical operators help you make decisions by combining or changing true/false values.

Checking if two conditions are both true before doing something.
Doing something if at least one condition is true.
Reversing a true or false value to its opposite.
Making complex decisions by joining multiple true/false checks.
Controlling program flow based on multiple rules.
Syntax
Ruby
condition1 && condition2  # true if both are true
condition1 || condition2  # true if at least one is true
!condition               # true if condition is false

&& means AND: both sides must be true.

|| means OR: one or both sides can be true.

! means NOT: reverses true to false and false to true.

Examples
Both sides are not true, so result is false.
Ruby
true && false  # => false
At least one side is true, so result is true.
Ruby
true || false  # => true
NOT true becomes false.
Ruby
!true  # => false
Inside parentheses is true, NOT makes it false.
Ruby
!(false || true)  # => false
Sample Program

This program checks two true/false values using AND, OR, and NOT operators and prints messages based on the results.

Ruby
a = true
b = false

if a && b
  puts "Both are true"
elsif a || b
  puts "At least one is true"
else
  puts "None are true"
end

puts "Not a is #{!a}"
OutputSuccess
Important Notes

Remember, && stops checking as soon as it finds a false (short-circuit).

|| stops checking as soon as it finds a true (short-circuit).

Use parentheses to make complex conditions clear and avoid mistakes.

Summary

Logical operators combine or reverse true/false values.

&& means both must be true, || means one or both can be true, ! reverses true/false.

They help control decisions in your program.