Ruby OOP — Classes, Objects, initialize — Complete Beginner Guide
Learning Objectives
- Define a class and create objects from it
- Set up state with initialize and instance variables
- Expose behavior through instance methods
- Use attr helpers for readable accessors
- Understand the relationship between classes and objects
What Is Object-Oriented Programming
Object-oriented programming, or OOP, organizes software around objects that bundle data and behavior together. Instead of scattering related variables and functions across a file, you model real-world concepts as cohesive units.
Ruby is a pure object-oriented language: every value is an object, even numbers and classes themselves.
Defining a Class
A class is a blueprint describing shared attributes and behaviors.
class Dog
def bark
puts "Woof!"
end
end
The class keyword opens the definition, and instance methods defined inside describe what every dog can do.
Creating Objects
Instantiate objects with the new method.
rex = Dog.new
rex.bark
fido = Dog.new
fido.bark
Each call to new returns a distinct object. Both objects share the same abilities defined in the class but can hold different internal state.
The initialize Method
initialize runs automatically whenever you call new. Use it to set up the object's starting state.
class Dog
def initialize(name, breed)
@name = name
@breed = breed
end
def intro
puts "I am #{@name}, a #{@breed}"
end
end
rex = Dog.new("Rex", "Labrador")
rex.intro
Instance variables store per-object data. Because each object has its own copies, rex's name never collides with another dog's name.
Reading and Writing Attributes
Directly reaching into instance variables from outside the object breaks encapsulation. Ruby provides accessor helpers.
attr_accessor
class Book
attr_accessor :title, :pages
def initialize(title, pages)
@title = title
@pages = pages
end
end
b = Book.new("Eloquent Ruby", 300)
puts b.title
b.pages = 320
attr_accessor creates both a reader and a writer method. Use attr_reader when you only want to read, and attr_writer when you only want to update from outside.
Methods That Describe Behavior
Good classes expose verbs that make sense for the object.
class Counter
def initialize
@count = 0
end
def increment
@count += 1
end
def value
@count
end
end
c = Counter.new
c.increment
c.increment
puts c.value
Callers interact through meaningful methods rather than poking at internal variables directly.
Class vs Instance Perspective
| Concept | Belongs to | Example |
|---|---|---|
| Instance variable | One object | That dog's name |
| Instance method | Every object | Every dog can bark |
| Class method | The class itself | Finding dogs in a repository |
| Class variable | All instances | Number of dogs created |
Class methods are defined with def self and describe operations on the class rather than a single instance.
Why OOP Helps
- Modeling: Code mirrors real concepts such as users, orders, or tickets
- Encapsulation: Internal state stays protected behind methods
- Reuse: Many objects share one class definition
- Testing: Small objects with clear interfaces are easier to verify
As programs grow, OOP keeps responsibilities organized and prevents a single file from becoming overwhelming.
Common Beginner Mistakes
- Forgetting to call initialize's parameters when using new
- Exposing raw instance variables with public access when methods would be safer
- Creating classes that do too many unrelated jobs
- Confusing class-level and instance-level methods
Start small: one clear responsibility per class is a reliable rule of thumb.
Object Identity vs Equality
Two objects may hold the same data yet occupy different places in memory. The equal sign with two equals checks whether two references point to the very same object, while the triple equal sign or the eql method checks value equality depending on context. Understanding this distinction prevents confusion when comparing custom objects in your code.
Instance vs Class Methods
The self keyword inside a class body refers to the class itself, while inside an instance method it refers to the object. Defining a method under class self creates a class level method useful for factories and configuration. Defining it normally creates an instance method available on every object created from that class. Keeping this distinction clear prevents many common beginner mistakes when organizing code.
Attribute Readers and Writers
The attr reader macro creates getter methods for instance variables automatically, and attr writer creates setters. Using attr access combines both. These macros reduce boilerplate significantly compared with writing each method by hand while keeping the public interface of your class explicit and discoverable.
Key Takeaways
💡
- Classes are blueprints; objects are instances created with new
- initialize sets starting state when an object is born
- Instance variables prefixed with the at sign store object-specific data
- attr_reader, attr_writer, and attr_accessor generate accessors
- OOP bundles data and behavior, making larger programs manageable
Practice Questions
- Write a Student class whose initialize takes name and grade.
- What happens automatically when you call SomeClass.new?
- Difference between attr_reader and attr_accessor?
- Create a class method using def self for your class.
- Why should instance variables not be accessed directly from outside an object?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions