Ruby Classes and Objects

An object is a collection of data (variables) and methods. A class is a blueprint for creating such an object.

Before we learn about objects, let's first understand classes in Ruby.


Ruby Classes

A class is like a blueprint for creating objects.

We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc.

Based on these descriptions, we build the house (here, the house is the object).

Since many houses can be made from the same description, we can create many objects from a class.


Defining a Class in Ruby

We use the class keyword to create a class in Ruby. For example,

class ClassName
  # Class definition
end

Here, we have created a class named ClassName. All the code that defines the class goes between the class keyword and the end keyword.

Note: Class names should be written in PascalCase, i.e., the first letter of each word should be capitalized.

Example

class Dog
  def bark
      puts "Woof!"
  end
end

Here,

  • Dog - The name of the class.
  • bark - A method inside the class that prints the string "Woof!".

Ruby Objects

An object is called an instance of a class. You can create an object by using .new after the class name like this:

object_name = ClassName.new

Example

class Dog
  def bark
      puts "Woof!"
  end
end

# Create objects of the class
dog1 = Dog.new
dog2 = Dog.new

Here, dog1 and dog2 are objects (instances) of the Dog class. Now, we can use this object to access the method defined in the class.

Note: Use snake_case for object names and method names in Ruby, like dog1, bark, wag_tail, etc.


Access Methods Using Objects

Once you've created an object/instance, you can use it to access instance methods defined inside the class. For example,

class Dog
  # Instance method
  def bark
      puts "Woof!"
  end
end

# Create an object of the class
dog1 = Dog.new

# Access the 'bark' method using dog1 object
dog1.bark

Output

Woof!

Here, we created an object named dog1.

As you can see, we accessed the bark method defined inside the Dog class using the code dog1.bark.

Note: Here, bark is called an instance method because it's called on an instance/object of the class. You can also define class methods that are called on the class itself, not its instances. You'll learn about those later.


Ruby Instance Variables

Instance variables store information about an object. They always start with @ and are available throughout the object. For example,

class Dog

  # Initializer method to initialize instance variables
  def initialize

      # Create and initialize instance variables
      @name = "Maple"
      @breed = "Border Collie"
  end

  # Instance method
  def greet
      puts "Woof! My name is #{@name} and I'm a #{@breed}."
  end
end

dog1 = Dog.new
dog1.greet

Output

Woof! My name is Maple and I'm a Border Collie.

Here, @name and @breed are instance variables of the Dog class.

Notice that we've used the initialize method to create and initialize the instance variables — it's the preferred way to perform this task.

Let's learn about this method next.


Ruby initialize Method

In Ruby, the initialize method is a special method that is automatically called when a new object is created from a class.

It sets up (or "initializes") the instance variables of an object when it's first created.

Note: The initialize method doesn't need to be called manually — it runs automatically when you create an object with .new.

Example

class Dog

  # Initializer method to initialize instance variables
  # Takes parameters 'name' and 'breed'
  def initialize(name, breed)

      # Assign arguments to the instance variables
      @name = name
      @breed = breed
  end

  # Instance method
  def greet
      puts "Woof! My name is #{@name} and I'm a #{@breed}."
  end
end

# Create an object
# Pass "Honey" and "Wolfdog" as arguments to initialize
dog1 = Dog.new("Honey", "Wolfdog")
dog1.greet

# Create another object and pass another set of arguments
dog2 = Dog.new("Maple", "Border Collie")
dog2.greet

Output

Woof! My name is Honey and I'm a Wolfdog.
Woof! My name is Maple and I'm a Border Collie.

Here, the initialize method accepts two arguments, which are stored in the name and breed parameters.

The values of these parameters are then assigned to the instance variables @name and @breed.

Note: Here, name and @name are different variables. The same goes for breed and @breed.

Passing Arguments to the initialize Method

We pass arguments to initialize when creating the object like this:

# Pass "Honey" and "Wolfdog" as arguments
dog1 = Dog.new("Honey", "Wolfdog")

# Pass "Maple" and "Border Collie" as arguments
dog2 = Dog.new("Maple", "Border Collie")

Example: Ruby Class and Objects

# Define a Circle class
class Circle
  def initialize(radius)
      @radius = radius
  end

  # Instance method that returns area of circle
  def calculate_area
      3.14 * @radius * @radius
  end
end

# Create a circle object with radius 7
circle = Circle.new(7)

# Call the instance method and store its value in a variable
circle_area = circle.calculate_area

# Print the area of the circle
puts "Area of the Circle: #{circle_area}"

Output

Area of the Circle: 153.86

In the above example, we defined a class named Circle with the following components:

  • @radius - An instance variable that stores the radius of the circle.
  • initialize - An initializer method to create and initialize the instance variable(s).
  • calculate_area - An instance method that returns the area of the circle.

We then created an object named circle and passed 7 as an argument to its initializer.

# Create a circle object with radius 7
circle = Circle.new(7)

This value is then assigned to the @radius instance variable.

Finally, we accessed its calculate_area method using the . notation:

# Call the instance method and store its value in a variable
circle_area = circle.calculate_area

Frequently Asked Question

Can we access instance variables outside the class?

Unlike instance methods, we cannot directly access instance variables outside the class using the . notation. For example,

class Dog
  def initialize(name, breed)
      @name = name
      @breed = breed
  end
end

dog1 = Dog.new("Honey", "Wolfdog")

# Invalid: Accessing instance variable 'name'
# NoMethodError: undefined method 'name' for an instance of Dog
puts dog1.name

# Invalid: Accessing instance variable 'breed'
# NoMethodError: undefined method 'breed' for an instance of Dog
puts dog1.breed

There are indirect ways to access instance variables outside the class, such as using the attr_accessor method. For example,

class Dog

  # Use attr_accessor on instance variables
  attr_accessor :name
  attr_accessor :breed
    
  def initialize(name, breed)
      @name = name
      @breed = breed
  end
end

dog1 = Dog.new("Honey", "Wolfdog")

# Access instance variables
puts dog1.name
puts dog1.breed

Output

Honey
Wolfdog

This program works because attr_accessor automatically creates name and breed methods for reading and writing those variables.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges