OOP Intro

What is it that the entire world, that surrounds you, consists of? Molecules? Atoms? That too, but objects is actually the word I'm searching for. Everything in the world is an object. Molecules and atoms are objects. The awesome car in your garage is an object. Planet Earth is an object. You and I are objects. As you probably have realized object is an extremely flexible term that can be used to describe practically everything. Why am I telling you this?

As a programmer you will often find yourself in need of representing objects in your software. If you're making a contact relationship manager, for instance, you will need some way to represent people and businesses that has some relationship to the business that uses your CRM. Ruby solves this problem by letting you declare classes. A class is a reusable piece of code that represents a real-world physical object, like a person, or a virtual object, like a file on your file system. Please go ahead and start irb if you haven't already and type the following lines:

class Person
end

It looks like this:

How to declare a class.

The first line starts the declaration of the Person class, the second line ends it. We have told Ruby that we want to represent people in our program. Simple, huh?

Let's try and save a new Person in memory.

person = Person.new

That line tells Ruby to make a new instance of your Person class. You can have multiple people represented in your program that uses the same declaration:

another_person = Person.new

Now we have two people. A person has a name, a gender, and a birthday. Next we will discuss how to assign to and retrieve these kinds of values from instances of our Person class.

declare_class.png - How to declare a class. (41 KB) David Knorr, 08/02/2009 03:32 pm

Also available in: HTML TXT