Objects Are Instances of Classes

Learn the relationship between classes and objects.

Objects have classes

As mentioned before when we run a Ruby program, space is created and populated with objects as defined by our program. These things interact and do useful stuff using the methods we call.

We can see that objects have classes when we ask the object for its class:

Press + to interact
print "this is a string".class

Here’s another way we can ask the same question in Ruby:

Press + to interact
print "this is a string".is_a?(String)

So, the actual string knows that it’s a String, that is, it’s an instance of the class String. We can do this for any object. For example, 1.is_a?(Numeric) also returns true.

Another way to put it is that an object is an instance of its class. Similarly, the creation of an object can be expressed as the class being instantiated.

What do objects of the same class have in common?

Classes have many characteristics, but most importantly, every class defines a number of methods. Whenever a new object is instantiated from this class, this new object gets (inherits) all methods associated with the class. So, the class dictates what kind of methods its instances can have. We discuss this in more detail next.