Ruby operators are special symbols that perform specific operations on one or more operands. They are essential for manipulating data and controlling program flow in Ruby.
Arithmetic operators perform mathematical calculations on numeric values.
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus)**
(Exponentiation)Example:
a = 10
b = 3
puts a + b # Output: 13
puts a - b # Output: 7
puts a * b # Output: 30
puts a / b # Output: 3
puts a % b # Output: 1
puts a ** b # Output: 1000
Comparison operators are used to compare two values and return a boolean result.
==
(Equal to)!=
(Not equal to)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)<=>
(Spaceship operator)Example:
x = 5
y = 10
puts x == y # Output: false
puts x != y # Output: true
puts x > y # Output: false
puts x < y # Output: true
puts x >= 5 # Output: true
puts y <= 9 # Output: false
puts x <=> y # Output: -1 (x is less than y)
Logical operators are used to combine multiple conditions.
&&
(AND)||
(OR)!
(NOT)Example:
a = true
b = false
puts a && b # Output: false
puts a || b # Output: true
puts !a # Output: false
Assignment operators are used to assign values to variables.
=
(Simple assignment)+=
(Add and assign)-=
(Subtract and assign)*=
(Multiply and assign)/=
(Divide and assign)%=
(Modulus and assign)**=
(Exponentiate and assign)Example:
x = 5
x += 3 # Equivalent to x = x + 3
puts x # Output: 8
y = 10
y *= 2 # Equivalent to y = y * 2
puts y # Output: 20
Ruby follows a specific order of precedence for operators. Understanding this order is crucial for writing correct expressions.
Precedence | Operator |
---|---|
1 (Highest) | ** |
2 | !, ~, unary + |
3 | *, /, % |
4 | +, - |
5 | <<, >> |
6 | & |
7 | ^, | |
8 | <, <=, >, >= |
9 | ==, !=, ===, =~, !~ |
10 | &&& |
11 | || |
12 (Lowest) | .., ... |
==
operator with floating-point numbers due to precision issues.Understanding Ruby operators is crucial for effective programming. They form the foundation for Ruby If-Else Statements, Ruby Loops, and other control structures. As you progress, you'll find operators essential in working with Ruby Arrays and Ruby Hashes.