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:

Ruby
class GameCharacter
  # Constructor method to initialize attributes
  def initialize(name, health, strength)
    @name = name       # instance variable for name
    @health = health   # instance variable for health
    @strength = strength   # instance variable for strength
  end

  # Method to simulate an attack
  def attack(target)
    target.health -= @strength  # Reduces target's health by strength
  end

  # Accessors to allow reading and modifying instance variables externally
  attr_accessor :name, :health, :strength
end

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.

Ruby
character_1 = GameCharacter.new("Hero", 100, 20)
character_2 = GameCharacter.new("Villain", 80, 15)

puts character_1.name  # Output: Hero
puts character_2.health  # Output: 80

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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal