Ruby Operators: A Comprehensive Introduction


Introduction to Operators

Operators in Ruby are symbols or keywords used to perform operations on data. They play a crucial role in arithmetic, comparison, and logical operations. In this guide, we'll explore various types of operators in Ruby and how to use them effectively.


Arithmetic Operators

Arithmetic operators are used for mathematical calculations:


addition_result = 10 + 5       # Addition
subtraction_result = 20 - 8 # Subtraction
multiplication_result = 6 * 4 # Multiplication
division_result = 30 / 3 # Division
modulo_result = 17 % 4 # Modulo (Remainder)

Comparison Operators

Comparison operators are used to compare values and return boolean results:


equal_result = 5 == 5          # Equal to
not_equal_result = 10 != 7 # Not equal to
greater_than_result = 15 > 10 # Greater than
less_than_result = 20 < 25 # Less than
greater_or_equal_result = 30 >= 30 # Greater than or equal to
less_or_equal_result = 40 <= 50 # Less than or equal to

Logical Operators

Logical operators are used to combine or modify boolean values:


logical_and = true && false     # Logical AND
logical_or = true || false # Logical OR
logical_not = !true # Logical NOT

Assignment Operators

Assignment operators are used to assign values to variables:


x = 10
y += 5 # Equivalent to y = y + 5
z -= 3 # Equivalent to z = z - 3

Bitwise Operators

Bitwise operators work at the binary level:


bitwise_and = 5 & 3     # Bitwise AND
bitwise_or = 5 | 3 # Bitwise OR
bitwise_xor = 5 ^ 3 # Bitwise XOR
bitwise_not = ~5 # Bitwise NOT
left_shift = 5 << 2 # Left shift by 2 bits
right_shift = 8 >> 2 # Right shift by 2 bits

Conclusion

Ruby offers a wide range of operators that enable you to perform various operations on data. Understanding how to use these operators is crucial for writing effective and efficient code.


Practice using these operators in your Ruby programs to become a skilled Ruby developer. For more information, refer to the official Ruby documentation.


Happy coding!