Use when working with Ruby's object-oriented programming features including classes, modules, inheritance, mixins, and method visibility.
allowed-tools
["Bash","Read","Write","Edit"]
Ruby Object-Oriented Programming
Master Ruby's elegant object-oriented programming features. Ruby is a pure object-oriented language where everything is an object.
Class Definition
Basic Class Structure
classPerson# Class variable (shared across all instances)@@count = 0# ConstantMAX_AGE = 150# Class methoddefself.count
@@countend# Constructordefinitialize(name, age)
@name = name # Instance variable
= age
+=
person = .new(, )
puts person.introduce
person.name =
@age
@@count
1
end
# Instance method
def
introduce
"Hi, I'm #{@name} and I'm #{@age} years old"
end
# Attribute accessors (getter and setter)
attr_accessor
:name
attr_reader
:age
# Read-only
attr_writer
:email
# Write-only
end
Person
"Alice"
30
"Alicia"
Method Visibility
classBankAccountdefinitialize(balance)
@balance = balance
end# Public methods (default)defdeposit(amount)
@balance += amount
log_transaction(:deposit, amount)
enddefbalance
format_currency(@balance)
end# Protected methods - callable by instances of same class/subclassprotecteddeflog_transaction(type, amount)
puts "[#{type}] #{amount}"end# Private methods - only callable within this instanceprivatedefformat_currency(amount)
"$#{amount}"endend
Inheritance
Single Inheritance
classAnimaldefinitialize(name)
@name = name
enddefspeak"Some sound"endendclassDog < Animaldefspeak"Woof! My name is #{@name}"end# Call parent method with superdefintroducesuper# Calls parent's speak method
puts "I'm a dog"endend
dog = Dog.new("Buddy")
puts dog.speak
Method Override and Super
classVehicledefinitialize(brand)
@brand = brand
enddefstart_engine
puts "Engine starting..."endendclassCar < Vehicledefinitialize(brand, model)
super(brand) # Call parent constructor@model = model
enddefstart_enginesuper# Call parent method
puts "#{@brand}#{@model} is ready to drive"endend
moduleGreetabledefgreet"Hello!"endendclassPersonincludeGreetable# Adds as instance methodendclassCompanyextendGreetable# Adds as class methodendPerson.new.greet # WorksCompany.greet # Works
classPersonincludeComparableattr_reader:agedefinitialize(name, age)
@name = name
@age = age
enddef<=>(other)
age <=> other.age
endend
people = [Person.new("Alice", 30), Person.new("Bob", 25)]
puts people.sort.map(&:age) # [25, 30]
Class Variables vs Instance Variables
classCounter@@count = 0# Class variable (shared)@instances = [] # Class instance variable (not shared with subclasses)definitialize@@count += 1enddefself.count
@@countendend
Best Practices
Prefer composition over inheritance for complex relationships
Use modules for mixins to share behavior across unrelated classes
Keep classes small and focused (Single Responsibility Principle)
Use attr_accessor/reader/writer instead of manual getters/setters
Make use of private/protected to encapsulate implementation details
Prefer instance variables over class variables to avoid unexpected sharing
Use Struct for simple data objects instead of full classes
Override to_s for debugging to provide meaningful string representations
Anti-Patterns
❌ Don't use class variables unnecessarily - they're shared across inheritance hierarchy
❌ Don't create god objects - keep classes focused and small
❌ Don't expose internal state - use methods instead of direct instance variable access
❌ Don't overuse inheritance - prefer composition or modules
❌ Don't ignore visibility modifiers - they exist for encapsulation
Related Skills
ruby-metaprogramming - For dynamic class/method generation
ruby-blocks-procs-lambdas - For functional programming patterns