I recently started learning to programme in ruby. In various sources, I came along a term that ruby is a real object-oriented language. In this post, I’ll try to share my understandings how a ruby object is created and how they work behind the scene.
For executing our snippets of code, we are going to use ruby console. The irb and pry are two most widely used ruby consoles. In this post, I am going to use pry cause so far I learned it has slight advantages over irb. But we wouldn’t discuss which is better now, that can be another topic to discuss.
To start with, let’s declare a
class. In ruby, to create a class, we need to start with
class keyword. Let’s go to
pry and type the following code.
If you run the above ruby code, it will execute and print “A class is an object“. When we write a class using the class keyword ruby creates an object of class Class. So A isn’t a class here. It’s an object referencing the class Class.
Now again go to the pry and type A.class. It shows the class name of A was instantiated from, and which is Class.
Let’s create an object of A. To do so in ruby, type
a = A.new. Here, new is a method of object A. We can create a new object of A by calling its new method. So now a is an object of A. At this point, if we type
a.class in the console, it will show A.
While we are using pry to execute ruby code, if you do a double tap on
TAB after giving a dot(.) on an object, it would list its all the methods.
Let’s explore another example. Type
steve = "Captain". This will create an object named steve containing a string object. If we type
steve. and double tap on
TAB, it will show all the methods. if we look closely, we can see there are 160 methods available the string object.
Earlier we saw, calling
class method of an object return the object from which it was instatiated. If we type
steve.class it retuns String.
Now, take another object
stark = "Jarvis". It will also have the same number of methods in it. Also
stark.class returns String, which is fine and it has 160 methods. So
steve are objects of string, they share the same number of methods.
We have an option in ruby to open an object and add methods to it. Let’s do it. Look closely at the below example.
We just opened the
stark object and added a method named
suit to it. This method will be only available to
stark object. As
stark is an object of string it will have all the methods of string and