Having fun with Classes

Let's create a dog!

May 9, 2015

Learning classes is essential for any object-oriented programmer. Classes are like blueprints. It's their job to encapsulate data and the behaviors that will act on that data. I'm going to use an example that I think can illustrate the concept of a class in a simple way. We're going to make a class called Frenchie. (Yup, I'm a fan of French bulldogs)

Creating a class is as simple as:

In order for your program to know about a Frenchie object, we need to create an initialize method into which we'll pass in data about a particular French bulldog. Your initialize method holds this data in instance variables, which are preceded by an @ symbol. Let's take a look:

Ruby has some convenient built-in ways for you to access and change this data. They are called attr_reader, attr_writer, attr_accessor. With our example, we want to make :name, :age, and :gender accessible through attr_reader, which simply allows you to see the data, not change it. attr_writer allows you to change data, and attr_accessor allows you to do both. We'll make our age and weight both accessible and readable, since these can change over time, whereas the others can't (unless you rename your dog, which would be weird). This is how you do it:

Now let's do something fun with our data! We'll create a method to print out our Frenchie stats. And all we have to do to access what's in our instance variables is reference our attr_ methods by putting them inside interpolation brackets!:

Notice above that we can call methods from other methods! Our young_old method determines whether or not your Frenchie is young, kinda old, or really old depending on his age. These numbers are somewhat specific to this breed. If we had a Labrador class, for example, our numbers might be different. Technically, we could have had a Dog class from which class breeds inherit from, and they could have customized methods for breed-specific data. But anyway, let's get onto to instantiating our Frenchie!

Here's what will output:

All that data just from calling our method show on our dog! And also see that we can access its age just by calling .age on the object. That's it for now. Hope you enjoyed my post. Thanks for reading!