Ruby - Comparison operators

1. Introduction

In Ruby, comparison operators play a crucial role in decision-making. These operators compare two values and return either true or false based on the result of the comparison. Being acquainted with them is fundamental to building conditions and controlling the flow of your program.

2. Program Steps

1. Initialize two variables with values for comparison.

2. Apply various comparison operators to evaluate these values.

3. Display the outcome of each comparison.

3. Code Program

# 1. Initializing two variables for comparison
a = 15
b = 25
# 2. Applying various comparison operators
# Checking equality
puts "Is 'a' equal to 'b'? #{a == b}"  # 3
# Checking inequality
puts "Is 'a' not equal to 'b'? #{a != b}"  # 4
# Checking greater than
puts "Is 'a' greater than 'b'? #{a > b}"  # 5
# Checking less than
puts "Is 'a' less than 'b'? #{a < b}"  # 6
# Checking greater than or equal
puts "Is 'a' greater than or equal to 'b'? #{a >= b}"  # 7
# Checking less than or equal
puts "Is 'a' less than or equal to 'b'? #{a <= b}"  # 8
# Spaceship operator: Returns 0 if both values are equal, 1 if the left-hand side is greater, or -1 if the right-hand side is greater.
puts "Result of spaceship operator between 'a' and 'b': #{a <=> b}"  # 9

Output:

Is 'a' equal to 'b'? false
Is 'a' not equal to 'b'? true
Is 'a' greater than 'b'? false
Is 'a' less than 'b'? true
Is 'a' greater than or equal to 'b'? false
Is 'a' less than or equal to 'b'? true
Result of spaceship operator between 'a' and 'b': -1

Explanation:

1. Ruby provides a set of comparison operators to compare values.

2. The result of these operations is always true or false.

3. The == operator checks if the values of two operands are equal.

4. The != operator checks if the values of two operands are not equal.

5. The > operator checks if the value on its left is greater than the one on its right.

6. The < operator checks if the value on its left is less than the one on its right.

7. The >= operator checks if the value on its left is greater than or equal to the one on its right.

8. The <= operator checks if the value on its left is less than or equal to the one on its right.

9. The <=> is called the spaceship operator. It's useful for sorting as it returns 0 if both values are equal, 1 if the left-hand side is greater, or -1 if the right-hand side is greater.


Comments