Understanding Ruby Classes: Constructors and Methods

Revisiting Ruby Classes

Let's continue working with classes using a Robot example to explore how Ruby classes serve as blueprints for creating objects. Here's a basic class definition:

Ruby
class Robot
end

robot_instance = Robot.new

At this stage, the Robot class is like an empty shell. It exists but doesn't know how to do anything. To make it functional, it needs attributes and methods.

Deep Dive into Constructors

A constructor is a special method that initializes an object when it's created. In Ruby, the constructor is the method named initialize. It sets up—or constructs—our new objects with the necessary initial states.

Here, we upgrade the Robot class with a constructor:

Ruby
class Robot
  def initialize(name, color)
    @name = name
    @color = color
  end
end

robot_instance = Robot.new("Robbie", "red")  # Robbie, a red robot, is born!

In this case, the initialize method gets automatically called when we create a new Robot instance, setting the name and color attributes. It's always good practice to use constructors like initialize to ensure each instance starts with the correct initial values.

Multiple Constructors with Default Parameters

Having one constructor is great, but what if we want more flexibility in setting up our robots? In Ruby, we can provide default values for parameters to offer similar functionality.

Here's a default color for our robots:

Ruby
class Robot
  def initialize(name, color='grey')
    @name = name
    @color = color
  end
end

robot_instance = Robot.new("Robbie", "red")  # Red Robbie
robot_instance2 = Robot.new("Bobby")  # Grey Bobby, no color provided

With default parameters, color becomes optional. When we don't specify it, the robot is 'grey' by default.

Class Methods

Class methods provide additional behaviors for our objects, acting like commands that define how objects interact and perform actions.

This Robot class allows the robots to introduce themselves:

Ruby
class Robot
  def initialize(name, color='grey')
    @name = name
    @color = color
  end

  def say_hello
    puts "Hello, I am #{@name} and I am #{@color}."
  end
end

robot_instance = Robot.new("Robbie", "red")
robot_instance.say_hello  # Robbie says: "Hello, I am Robbie and I am red."`

The say_hello method allows our robot instance to interact and even communicate.

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