Notifications
Clear all
Topic starter 01/08/2025 11:39 pm
Ruby classes are the heart of object-oriented programming in Ruby—they let you create reusable blueprints for objects with both state (data) and behavior (methods). Here’s a friendly walk-through:
🏗️ Defining a Class
class Dog
def initialize(name, breed)
@name = name
@breed = breed
end
def speak
puts "#{@name} says woof!"
end
end
class
starts the class definitioninitialize
is the constructor called when a new object is created@name
and@breed
are instance variables, unique to each object
🐾 Creating an Object
my_dog = Dog.new("Fido", "Labrador")
my_dog.speak # Outputs: Fido says woof!
🔄 Accessors and Readers
Ruby has special helpers to access or modify instance variables:
class Dog
attr_reader :name # allows reading @name
attr_writer :breed # allows modifying @breed
attr_accessor :name, :breed # read and write both
end
🧬 Inheritance
You can make one class inherit from another:
class Puppy < Dog
def speak
puts "#{@name} squeaks!"
end
end
💡 Other Goodies
- Class methods: define with
self.method_name
- Constants: use all caps like
BREED_TYPES = ['Labrador', 'Poodle']
- Modules: share behavior across classes (like mixins)
Ruby makes OOP surprisingly elegant—just the right mix of readable and powerful.