Ruby Classes

Blueprints for Code

November 30, 2015

Ruby Classes are a built-in way to organize information and bring your objects to life. They are used to define a type of object, and then give that object functionality through methods.

In this example, we are going to make a Pet Class. To start off we need to decide what characteristics each pet should have when we create them. To keep it simple, let's initialize each Pet with a name and a type.

Now, when I make a new Pet, I need to pass in two arguments.

You may notice those "@" signs before the variables inside the initialize method. These are called instance variables, and they are used to describe an instance of a method. In this case, our instances are "my_pet" and "my_other_pet". The instance variables assigned to each of those instances will travel with the instance across class methods. This means that I can access the name and type of pet that my_pet is OUTSIDE the initialize method!

To see this in action, I've created a name method, and a type method. They're pretty simple, they just display these attributes of the instance we've created. Because they are class methods in class Pet, I can call them with the .method_name method call convention.

There's a cleaner way to create these class methods in Ruby, using the attribute accessor (a combination of what's called "getter" or reading methods, and "setter" or writing methods.) Below, I've used this technique to eliminate the need for the def name and def type methods. The below code will produce the same output as above

So far, our pet doesn't do anything very interesting. So, lets' give him an activity.

Of course, you could do it this way, too:

Classes can be confusing at first, but if you think of them as blueprints that tell the instances of your object what to be and how to act, they become wonderfully helpful tools to create usable, interactive code!