In programming, objects are a conceptual way by which developers organize data and actions taken on that data. Why impose any order at all on a computer program? In practice, computer programs tend to evolve-- a lot. Existing features are tweaked and new features are added, constantly. Moreover, different programs might have some of the same functions; a developer shouldn't continually reinvent the wheel. So ideally code needs to be both highly adaptable to change and compartmentalized. That's where classes and objects come in. Classes are like the blueprints for objects, so let's create a class in Ruby:
In the real world, all objects, alive or inanimate, can be said to have attributes and behavior. Let's focus on attributes first. Attributes are the characteristics or qualities of the object. For example, a rock could have the attributes of color, weight, volume. A cat can have the attributes of color, weight, gender, breed. In a class, instance variables-- signified with the @ to start variable names-- are the attributes of an object. As it stands, our Person class is an empty husk. Let's add some attributes to our Person by adding sensible instance variables. The initialize
method is a method that's called when an object is first created, or instantiated. Naturally, that's a common place to give our instance variables (a Person's attributes in this case) their first values.
This is our basic blue-print for a Person. Let's create an instance of a Person. Or several instances! In fact, we can create as many Person objects as we want. Already, you might see the power of classes and objects: we can create as many objects as we want, but the code to do so resides in a single, tidy, compartmentalized, meaningful area.
In the real world, objects not only have attributes but behaviors. For example, a rock's behaviors could be: sit and roll. A cat's behaviors could be: sit, purr, meow, knock over stuff. In a class, the instance methods are the behaviors of an object. Let's give our Person class a behavior with the instance method introduce_self
:
Let's recreate our Person objects (not shown), and ask each of them to introduce_self
:
All the Person objects introduced themselves appropriately! This showcases an important quality about objects of the same type: each object shares instance methods but acts on its own set of instance variables data.
As demonstrated, any change to the Person class is a powerful ripple throughout all Person objects created thereafter. We don't have six sets of code for six different Person objects; instead, we have a single, generic template of code for all Person objects. It's highly reusable. And you can see how this lends to adaptability as a single, compartmentalized spot of code can command sweeping changes.
There is of course much, much more to Ruby classes (including the particulars of designing good vs poor ones), but hopefully this brief and basic introduction into Ruby classes and objects has been helpful.