Lesson 1
Classes and Objects in Ruby
Classes and Objects

Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries, we'll start from the basics.

Classes and objects are the building blocks of OOP. A class acts as a blueprint for creating objects, which are instances of the class. Understanding these basics is essential before moving on to more advanced OOP topics like inheritance, polymorphism, and encapsulation.

What You'll Learn

In this lesson, you'll learn how to define and use classes and objects in Ruby. We'll cover:

  1. Declaring and Defining Classes
  2. Creating Objects from Classes
  3. Using Constructors
Declaring and Defining Classes

In Ruby, a class is defined using the class keyword, and the constructor is defined with the initialize method. Here's a simple example:

Ruby
1# Defining a class named Person 2class Person 3 # Constructor that initializes the object with a name and age 4 def initialize(name, age) 5 @name = name 6 @age = age 7 end 8 9 # Method to display the object's data 10 def display 11 puts "Name: #{@name}, Age: #{@age}" 12 end 13end

In this snippet, we define a Person class with instance variables @name and @age and a method, display, which prints the object's data. Unlike in some other languages, Ruby does not require the explicit specification of data member accessibility (private), and we typically use instance variables prefixed with @.

Creating Objects from Classes

Once you have defined a class, you can create objects (instances of the class). Here’s how we can create and use objects of the Person class:

Ruby
1person = Person.new("Alice", 30) # Creating an object 2person.display # Displaying the object's data

Here, we create an object, person, with the name "Alice" and age 30, and call the display method to print the object's data directly. Ruby uses new for object creation, which automatically invokes the initialize method.

Instance variables belong to the instance of the class and retain their values as long as the object exists. They are not shared across instances, which means every object of the class will have its own separate @name and @age. This is a key feature in Ruby that supports encapsulation, allowing data to be tied directly to the instance.

Without initialize, object creation would still work, but no initial setup (like assigning @name and @age) would occur.

Understanding Attribute Accessors in Ruby

Attribute accessors in Ruby (attr_reader, attr_writer, attr_accessor) are crucial for managing instance variable access in a controlled manner. Here’s when you might use each:

  • When to Use attr_reader: Use attr_reader when you want the data to be readable but immutable after initialization. For example, @account_number in a bank account should only have a getter because it should not change once assigned. This approach maintains the integrity of values that should remain constant throughout the lifecycle of an object.

  • When to Use attr_writer: Use attr_writer when you want to allow modifications but don’t want the value to be directly readable. For instance, @password might have a setter but no getter for security reasons. This ensures that sensitive information is not exposed while still allowing for updates.

  • When to Use attr_accessor: Use attr_accessor for properties that require both reading and modification. For example, @address for a person might need both getter and setter methods as it can change over time. This flexibility ensures that the data can be accessed and altered as needed without additional layer of method definitions.

Why It Matters

You might wonder: why is this important?

Understanding classes and objects is critical because they enable you to model real-world entities in your programs. For instance, a Person class helps you create multiple person objects with different names and ages, enabling you to manage and manipulate data efficiently. This principle is the backbone of complex software systems.

With this knowledge, you will be better prepared to approach more advanced OOP techniques and design patterns, allowing you to write clean, modular, and scalable code. Let's get started with the practice section to gain more hands-on experience.

Ready to code? Let's dive in!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.