Ruby Classes and Objects Tutorial

  • Post author:
  • Post category:Ruby

In this section we will learn what the Classes and Objects are and how they are being used in Ruby.

Ruby and Object Oriented Programming:

Ruby is an object-oriented language! This means everything in Ruby is an object!

An integer number like 10, a string value like “hello”, a boolean value like true or false etc. they all are objects!

The word object at first might sound confusing because after all, we call a physical and touchable thing an object but not a written in-touchable thing in the world of programming!

But here’s why we consider values in Ruby language as objects:

In real world, a car for example, is a form of an object (Although a complicated one). The two main properties of an object like a car is that:

  • It has behavior: consider the word “behavior” as the capabilities a car can do. For example, it has a gas pedal that if we push, the car will start to move. Or it has a steering wheel where we can use to change the direction of the car and so many other behavior (capabilities).
  • It has state: For example, a car can stop, move, accelerate or decelerate, etc. These are the states of a car!

Now back to the programming language Ruby; we mentioned that a string value, for example, is an object. We call it object because not just a string value but every other value in Ruby has the two main properties of an object in the real world:

  • They all have behavior: in programming, these behaviors are represented using methods. For example, a string value has a method that allows you to convert its characters into uppercase or lowercase! It has methods that allow you to remove any white space from both sides of a string value. Or you can use an integer value and use one of its behavior (method) to convert that integer value into a string value (change its form) and many other behaviors that you can get from an object in Ruby.
  • They have State: Internally objects can have variables (AKA instance variable) that will hold a set of values and these values are changeable!

That’s why we say everything in Ruby is an object! This is because they have both behavior (methods) and changeable state (internal variables, AKA instance variables). Although note that sometimes we can have objects in Ruby without a changeable state!

Now so far we’ve been working with built-in objects (like string values, integer values, boolean values etc.) But in Ruby we’re not limited to just these built-in objects and we can create our own objects as well!

This is done using classes!

What is Class in Ruby?

A class is a blueprint, a plan if you will. It’s a structure where we define the state and behavior of the objects we want to create in our program.

Basically, using classes, we can define what behavior (AKA method) and state (AKA instance variable) we want to have for our object!

After creating a class, we can use it to build actual usable objects in our program that can be used to serve purposes in a program.

Alright, let’s see how we can create a class now.

How to declare a class in Ruby? (Defining Classes in Ruby)

class ClassName

#The body of the class

end

`class`: in order to create a class in Ruby, we start with the keyword `class`.

`ClassName`: after the class keyword comes the name of the class. This name could be anything, but it should follow the naming convention that we’ve mentioned for the names of variables. Also, the name of a class by convention starts with a capital letter and if the class name combines more than one word it’s suggested to use PascalCase format (Meaning each word should start with a capital letter).

`end`: the end clause defines the closing border of the class. Now within the body of the class we can define behavior (methods) and state (variable) and those objects that will be created from the class all will have these methods and variables.

Example: class in Ruby

class Person

#instance methods and variables goes here

end

In just a moment, we will explain what you can put in the body of a class and how to do it practically.

Members of a Class in Ruby

As mentioned before, we can put methods and variables within the body of a class. The methods we put in the body of the class are called instance methods and the variables are called instance variable.

Let’s see why they are called “instance method” and “instance variables”.

Ruby Instance Method

The methods that we create within the body of a class are called instance method. The word `instance` here means object. So when we say instance method, we mean object-methods, which means these methods belong to the future objects that will be created from our class.

Basically, we can use these objects to access the methods created in a class.

Note that there’s no difference between how we create an instance method and the usual methods we’ve been creating so far. The only difference is that we create an instance method in the body of a class.

Also remember that when creating an object from a class, the objects will have its own copy of the methods defined in the class! So if we create two objects from a class, then the instance methods will be copied for each object and hence each object will hold its own copy of the methods.

Example: creating instance methods in Ruby class

class Person 

    def say_hi (full_name)
        puts "Hello #{full_name}"
    end 

    def say_goodbye (full_name)
        puts "Good bye #{full_name}"
    end 
end 

In this example, the Person class defined two instance methods named `say_hi` and `say_goodbye` and each takes a parameter.

Note that other than defining these methods in the body of the class, there’s no difference in how we declared the methods.

Ruby Instance Variable

Instance variables are local variables for objects that will be created from a class. Instance variables define the state of an object.

Be aware that each object that is created from a class will have its own copy of instance variables created in a class.

That means if we changed the value of an instance variable for an object, that change won’t affect another object that is created from the same class because the other object has its own copy of the instance variables.

Note that after creating an instance variable, it is accessible within the body of any instance method created in the class!

Ruby Instance Variable Declaration Syntax:

In order to create an instance variable, we put the @ symbol in front of a variable name and define that variable inside an instance method.

For example:

@first_name

@last_name

@age

These three variables, if they were defined inside the body of an instance method in a class, they would become the instance variables of the future objects created using the class.

Example: creating instance variables in Ruby class

class Person 

    def instance_variables (first_name, last_name)
        @first_name = first_name
        @last_name = last_name
    end

    def print_full_name 
        puts "The full name is: #{@first_name} #{@last_name}"
    end 
end

In this example the `Person` class created two instance variables in the body of the `instance_variables` method named `@first_name` and `@last_name`.

Notes:

  • When creating an instance variable in the body of a method, as long as that method is not called and your program didn’t execute its body, the instance variables won’t exist! Basically, first the method or methods that contain instance variables should be called and after that your program will add instance variables to the object that is calling the methods. (More on this in just a bit)
  • Instance variables are not accessible directly from the objects that we create from a class! They are basically private from outside the class they are defined in. The only way of accessing an instance variables are through instance methods. (We will get into this one as well in just a bit)

Ruby What is Object?

After creating classes, it’s time for objects.

Objects are the built version of what we define in classes. Using objects, we can access the instance methods we’ve created in a class and call them to run a different sort of operations.

Alright, let’s see how we can build objects from a class.

How to Create Objects in Ruby?

In order to create an object from a class we use the name of the class and invoke the `new` method on that class to create an object from it.

Here’s the syntax:

ClassName.new

`ClassName`: this is the name of the class we want to create an object from.

`new`: this is the method we should call when want to create an object from a class.

`.`: between the ClassName and the `new` method we put the dot `.` operator to mention that the `new` method belongs to the `ClassName` class and we want to call this method in this class. Basically, the dot operator makes it clear on what Class the `new` method is getting invoked one.

Example: creating objects in Ruby

class Person 

    def instance_variables (first_name, last_name)
        @first_name = first_name
        @last_name = last_name
    end

    def print_full_name 
        puts "The full name is: #{@first_name} #{@last_name}"
    end 
end 

prs = Person.new

In this example, we’ve created a new object from the `Person` class and then made the `prs` variable to point to that object.

So now we can use the `prs` variable to access the object and invoke its instance methods.

How to Access Instance Methods of an Object in Ruby?

Alright, so far we’ve learned how to create an object from a class and now let’s see how to access the instance methods of our newly created object:

In order to access an instance method using an object, we use the name of the object (the variable that the object is assigned to) + the dot operator and then the name of the target instance method.

Example: accessing instance methods of an object in Ruby

class Person 

    def instance_variables (first_name, last_name)
        @first_name = first_name
        @last_name = last_name
    end

    def print_full_name 
        puts "The full name is: #{@first_name} #{@last_name}"
    end 
end 

prs = Person.new

prs.instance_variables("John","Doe")
prs.print_full_name

Output:

The full name is: John Doe

In this example, we’ve used the `prs` variable which is now representing our newly created object in order to call the two instance methods `instance_variables` and `print_full_name`.

Note:

As mentioned before, when creating an object, Ruby will put your object in the memory and takes a copy of all the instance methods defined in the class that is used for creating the object and put the copy of these methods for the new object. But the instance variables are not created yet for the new object!

Basically, as long as we don’t call the instance methods that have the instance variables, no instance variable will be assigned for the new object!

For this reason, we need to call those methods that have instance variables first in order to initialize the instance variables and then we can call other instance methods of the object that want to work (either take or modify) the instance variables.

For example, in the program above, if we first called the `print_full_name` we would’ve got error! This is because in the body of this method we’re trying to access two instance variable but they are not initialized yet! (The two instance variables of this program is in the body of the `instance_variables` method and as long as we don’t call this method, the new object won’t add them as part of its instance variables.

So in short: be careful and make sure you first call a method that initializes an instance variable and then call other instance methods that are actually working with the instance variables based on the assumptions that they are defined in the object.

Multiple Object from a Class in Ruby

When you have a class in a program, there’s no limit on how many object you want to create from that class.

Just remember that each object you create from a class, will have its own copy of the instance methods and instance variables and so if we modify the value of an instance variable in one object for example, the other object’s instance variable won’t take effect.

Example: creating multiple objects from a class in Ruby

class Person 

    def instance_variables (first_name, last_name)
        @first_name = first_name
        @last_name = last_name
    end

    def print_full_name 
        puts "The full name is: #{@first_name} #{@last_name}"
    end 
end 

prs = Person.new

prs.instance_variables("John","Doe")
prs.print_full_name

second_person = Person.new

second_person.instance_variables("Omid","Dehghan")
second_person.print_full_name

Output:

The full name is: John Doe

The full name is: Omid Dehghan

As you can see, we’ve created two objects from the `Person` class and each one of them has its own instance of variables with different values assigned to them.

More to Read:

Ruby Instance Variables Tutorial

Ruby Attribute Accessors Tutorial

Ruby Encapsulation Tutorial

Ruby Initialize Method Tutorial

Ruby Inheritance Tutorial

Leave a Reply