Classes in Ruby

As an object oriented programming language, Ruby uses something called classes to organize a group of objects that share certain attributes or methods.

Let's take one of my favorite TV shows as an example. If I wanted to write a program that stored data about some characters on futurama, I would start by creating a Futurama class.

The class declaration always starts with the keyword "class" followed by whatever name you assign to the class. Note that unlike variables, which start with lowercase, class names always start with an uppercase letter. The class closes much like you would expect with an "end" statement.

Now that we have created our class lets create and object of the class. When you create an object of a given class, that object is said to have been instantiated, or is now an instance of that class.

So now we have an object "character" which is an instance of the Futurama class, but it doesn't have any properties or methods yet. Let's say I wanted my Futurama class to store some data about some of the characters in the show. Let's start with some basics like name, species, and job description.

We've created a method called set_name which takes a string as an argument and then returns a string telling us that we have successfully created a character named Fry. Notice that much like pre-set methods in ruby, we call the method outside the class using dot notation and pass in the argument Fry as a string. We can follow similar protocols to add a couple more methods.

The first method in this code will run just fine, but something is not quite right about the set_species and the set_job methods. Specifically, Ruby tells me there is an undefined local variable in the method set_species. And Ruby is right; trying to use the local variable name outside the set_name method is just not possible using our current scope.

Lucky for us, this is an easy fix. In much the same way that we created instance objects of the Futurama class, we can also create instance variables using @ notation. It looks like this.

By assigning the local variable name to the instance variable @name we now have access to the instance variable @name throughout the Futurama class, not just in the set_name method. Now when we call each method outside the class, our output does exactly what we want it to

We could continue creating objects and adding new characters to our show, but the code would look remarkably similar. In fact, we might start to find that there would be an even easier way to manipulate all this data using an initialize method among other things outside the scope of this blog post.

While this quick tutorial shows the basics of using classes, instantiating objects, and instance variables to manipulate data, it hardly shows the power of class in Ruby. Once you master these basics and get comfortable using classes to encapsulate and manipulate data in no time.

Blog Archive

Coming Soon!