Ruby - Logical operators

1. Introduction

Logical operators in Ruby are used to determine the logic between variables or values. They play a crucial role in conditions and decision-making processes in programs.

2. Program Steps

1. Initialize sample variables.

2. Apply and demonstrate the logical operators on the initialized variables.

3. Code Program

# Initialize sample variables
a = true
b = false
# Logical AND
and_result = a && b
puts "Logical AND: #{a} && #{b} = #{and_result}"
# Logical OR
or_result = a || b
puts "Logical OR: #{a} || #{b} = #{or_result}"
# Logical NOT
not_result = !a
puts "Logical NOT: !#{a} = #{not_result}"
# Use of 'and' and 'or'
# These are lower precedence than their counterparts '&&' and '||'
c = nil
d = "Hello"
and_low_result = c and d
or_low_result = c or d
puts "Result of 'and' with lower precedence: #{and_low_result}"
puts "Result of 'or' with lower precedence: #{or_low_result}"


Logical AND: true && false = false
Logical OR: true || false = true
Logical NOT: !true = false
Result of 'and' with lower precedence:
Result of 'or' with lower precedence: Hello


1. The Logical AND (&&) operator returns true if both operands are true and false otherwise.

2. The Logical OR (||) operator returns true if at least one of its operands is true and false otherwise.

3. The Logical NOT (!) operator returns true if its operand is false and false if its operand is true.

4. The and and or operators work similarly to && and ||, but they have lower precedence. This can lead to unexpected results if not used carefully. For instance, in the example above, the or_low_result returns "Hello" because the assignment has a higher precedence than or.