Classes & Objects in Ruby

Kyle Le
3 min readDec 4, 2020

Ruby is an awesome Object-Oriented programming language which allows us to use many of data types. Like integer, string, float, or boolean.

But not all things in the world can be represented by just a string or a number. A lot of things are much more complicated such as a book, a machine, a tree, or even a person. So this is one of the reasons why Ruby is cool, that we can create our own data types.

That means I can create my own data type which can represent a book or a computer. Literally anything I want, I can create my own data types. And it’s called Class. A Class is simply a data type that I can define. And Class in Ruby can be created with keyword class

So let’s say I want to create a person, and here is what a person looks like in my program:

So a person must have a name, age and gender. So this is like a blueprint or a template for a person. Now that I just told Ruby what a person is, let’s create a specific person in our program. And this is called object. An Object is simply an instance of a Class. So in this case I will create a person object:

So basically I just created a specific person in my program, and that person is based on a class name Person. And like I defined in that class, a person will have a name, age and gender. So now I can say that:

In this way I just set all the attributes for that person. And I literally mean it:

I just printed all the attributes of the person object that I created, like name or gender or age. And Classes can have methods beside attributes. So in this case, a person can have personal acts right ? So I will define a method called speak in the Person class:

Now I will create another person to test out this method:

As we can see, I just created a person who is Sasha and let her speak.
So in the end, we can create a class, create instances of that class called objects,and we can refer to them directly. And that’s how classes and objects work, they allow you to create your own data types in Ruby.

And one cool thing in Ruby is that almost everything in Ruby is a object, but we can talk about this in other articles ;)

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

--

--

Kyle Le

I’m a Software Engineer who loves to write. My content is based on what I've learned and experienced every day