Understanding Ruby Classes: A Refresher on Attributes and Methods
Overview
Welcome! Today, we’re diving into Ruby classes, the foundation of Object-Oriented Programming (OOP) in Ruby. This lesson introduces the concept of classes as blueprints for objects. We’ll explore how to create classes and objects, understand the difference between them, and see how attributes and methods store and manipulate data within each object.
Ruby Classes Refresher
In Ruby, a class serves as a blueprint for creating objects. Each object, or instance of a class, has its own data (attributes) and can perform actions (methods). Imagine a video game character: each character has attributes like health or strength, and methods like attack or defend.
Here’s a simple GameCharacter class to illustrate these ideas:
Here, GameCharacter defines a blueprint for characters. The attributes @name, @health, and @strength store data specific to each character, while the attack method defines behavior each character can perform.
Creating Classes and Objects
In Ruby, creating an object is as simple as defining a class and calling new on that class. Each object created this way is an instance of the class and has its own copy of the class’s attributes.
Each instance, character_1 and character_2, has its own unique data, demonstrating how a class can produce multiple distinct objects.
Understanding Attributes in Ruby Classes
Attributes, represented by instance variables prefixed with @, hold data specific to each instance. In the GameCharacter class, @name, @health, and @strength are instance variables storing each character's state. In Ruby, instance variables are private by default, meaning they cannot be accessed directly from outside the class. Instead, we need getter and setter methods to retrieve and update these values.
