Forum

Learn Ruby Classes
 
Notifications
Clear all

Learn Ruby Classes

1 Posts
1 Users
0 Reactions
9 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

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 definition
  • initialize 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. 


   
Quote
Share: