Ruby Classes

I remember once my then girlfriend asking me what Objected Oriented was and me utterly failing at coming out with a simple clear answer. It was Albert Einstein who said, "If you can't explain it to a six year old, you don't understand it yourself." Not that I'm remotely suggesting that she shared similarities any way with a six year old because that would not be nice, to the six year old.

Simply put, Ruby Classes and Objects model real-world objects in intuitive ways. Classes group information together by creating a notion of object attributes and methods that are directly associated with specific objects. Classes are the mechanism to "construct" these objects, the blue print if you will, and contain information about said attributes and classes. Classes are one degree abstracted from objects in that they generalize a given object and allow you to repeatedly construct it with different attributes.

As I mentioned, Classes contain information about the attributes (data) and methods (functions that act on said data) of their objects. Let's go through them one-by-one in our Gear example.

First we define the initialize method. This helps you 'create' an object -- you use this method to generate a new Gear object. It is a function that takes four inputs: chainring, cog, rim, and tire. These inputs are then fed into the attributes that each Gear instance has, "@chainring", "@cog", "@rim" and "@tire". The "@" symbol is syntax and part of all 'instance variables', i.e. variables that your object contains once it is initialized.

In addition to the initialize method, there are several others methods that can act on each Gear object. In this case we have ratio and gear_inches. One divides the chainring by the cog size in order to calculate, you guessed right, the ratio. The other method, in turn uses the output from ratio to calculate the gear inches which is what cyclist (at least those in the United States) use compare bicycles that differ in both gearing and wheel size.

We have created a Class--a constructor, essentially--which generates Gear objects with associated data (attributes) and functions that act on said data (methods).