Notifications
Clear all
Topic starter 01/08/2025 11:12 pm
Ruby operators are the tools that let you manipulate data, make decisions, and control the flow of your program. Think of them as the verbs in Ruby’s language grammar 🧠🔧
➕ Arithmetic Operators
Used for basic math:
a = 10
b = 3
puts a + b # Addition → 13
puts a - b # Subtraction → 7
puts a * b # Multiplication → 30
puts a / b # Division → 3
puts a % b # Modulus → 1
puts a ** b # Exponentiation → 1000
📝 Assignment Operators
Used to assign and update values:
x = 5
x += 2 # x becomes 7
x *= 3 # x becomes 21
Other examples: -=
, /=
, %=
, **=
🔍 Comparison Operators
Used to compare values:
puts a == b # Equal → false
puts a != b # Not equal → true
puts a > b # Greater than → true
puts a < b # Less than → false
puts a >= b # Greater or equal → true
puts a <= b # Less or equal → false
puts a <=> b # Spaceship → 1 (a is greater)
🔗 Logical Operators
Used to combine conditions:
puts true && false # AND → false
puts true || false # OR → true
puts !true # NOT → false
🧬 Bitwise Operators
Operate on binary values:
puts 5 & 3 # AND → 1
puts 5 | 3 # OR → 7
puts 5 ^ 3 # XOR → 6
puts ~5 # NOT → -6
puts 5 << 1 # Left shift → 10
puts 5 >> 1 # Right shift → 2
📦 Range Operators
Create sequences:
puts (1..5).to_a # Inclusive → [1, 2, 3, 4, 5]
puts (1...5).to_a # Exclusive → [1, 2, 3, 4]
🧠 Bonus: Custom Operator Behavior
In Ruby, many operators are actually methods. You can redefine them in your own classes to customize behavior. For example:
class Fruit
attr_reader :name
def initialize(name)
@name = name
end
def ==(other)
name == other.name
end
end
Now two Fruit
objects with the same name will be considered equal.