Ruby Classes

A Newbies Guide to Development

December 20, 2015

Entering into anything new can be overwhelming and intimidating. I should know, I have chosen to enter the field of web development and I'm attending Dev Bootcamp. Dev Bootcamp (DBC) is a development bootcamp geared at taking you from newbie to a world class beginner in 18 weeks. It is going to be one of the most challenging experiences of my life. This blog series is designed to be an introduction to the world of development for the novice developer by a novice developer. By the end of this series I hope that you have had an opportunity to grow as much as I have.

Ruby Classes

I guess we have to first define what a Class is in Ruby, which in itself can be somewhat confusing. In Ruby, everything is an Object and you can think of Classes as the declaration of an Object. So a Class is the shell of an object and it is filled with the methods that define that Class. Let's take a look by declaring on new Class, we'll call it Dog.

One thing you'll notice is that classes are capitalized, that is kind of important. So let's create our Dog class: That's it, we're done! Well not really. We have the shell of our class, but we need to bring Dog to life and we need to start by initializing our Dog.

So puppy is a new instance of Dog and we have passed it the name = 'Atticus' and the breed = 'German Shepherd'. Within our class, @name and @breed are instance variables and can be used by all the methods within our class. Using instance methods we can now start to define the behaviors that control our Dog.

Let's start by adding another instance variable when Dog gets initialized, the instance variable will be @hungry and we'll initialize to false. We'll also create our first instance method feed.

We are on our way, but we need to do more with our Dog, otherwise how much fun is he? How about we create a new method bored.

All right, we are getting close to having a real Dog; let's add two more methods. The first method will make our Dog sleep and the second will be able to check on the status of our Dog.

Well, you did it! You created a new Dog Class in Ruby, and you are the proud owner of a new puppy! What is really amazing is just like in real life, you now have to care for your pet! So you better check in on him, I think he may be @hungry, @bored, or @tired.