Ruby Classes and Objects
(Page 1 of 4 )
In the previous articles, we got into some of the simpler aspects of Ruby. In this tutorial, we are going to cover the area of Classes and Objects. While still pretty basic in concept, Classes and Objects are powerful tools that will assist in your efforts to take over the world -- or at least to master all of the wonderful things that Ruby can do.
So put aside those 20-sided dice, pack up your Magic: the Gathering cards, and close that game of Civilization you have running on your computer. It's time to do something productive with that silicon box. Roll up your sleeves and let's get to work.
Class: You Have it or You Don't
It's true. Take Ben Franklin for example. He was classy enough to be a respected writer, inventor, and an ambassador to France for a nation about to be born -- plus hardcore enough to fly kites in thunderstorms. (He must have also been a ninja; I mean even Chuck Norris won't do that!). That's class. Unfortunately, Ben may have been a wise old man, but he didn't know anything about coding in Ruby, so this won't really help you.
An easy way to think of classes in Ruby is to consider the beverage industry (no, it isn't time for a beer yet). There are a wide variety of beverages to choose from. Soda, water, milk, juice, whatever Yoohoo is (delicious I think is the only real way to describe it), energy drinks, and Kool-Aid -- the poor man's champagne. Each of those (well not Yoo-hoo and Kool-Aid) would be considered a group of beverages, or a class. For instance, Soda is a class of beverages. Now within that class you can have a variety of unique drinks: Coca-Cola, Pepsi, Sprite, Dr. Pepper, Jolt, Mountain Dew (the nectar of the gods), etc.
Whether you know it or not, I just not only described Classes (the beverage type) but also Objects (the individual sodas that make up the Class). Put simply, the class acts as the type of an object. Class: Soda. Object: Mountain Dew.
The last thing you need to know is this: You use classes to create objects.
Next: Create a Class >>
More Ruby-on-Rails Articles
More By James Payne