Ruby Class Methods

So far we have been using classes in ruby to organize and manipulate data using built in or user defined methods. We call the objects instantiated within that class instance objects, and we similarly call the methods we define as instance methods. An instance object of a class contains all the variables and instance methods of the class to which it belongs.

As an example, here is a simple class definition with one instance method.

Class methods may be defined in a very similar sense, but instead of being an instance of the class, class methods are called on the class itself. It's important to remember that Ruby allows this because classes are also objects in Ruby, even though they contain other objects and methods.

To define a class method, we can use a Ruby keyword called self, which simply refers back to the current object. In the example below, self refers back to the class itself. There are other ways to write class methods, but for now let's keep it simple.

So when would I need to use a class method instead of an instance method?

Generally, instance methods are used to do the bulk of the work in classes. For example, if you needed to use a common string method like .length it would only make sense that you would likely call that method on an instance object string of a class rather than the class itself. We can, however, use class methods to gather information about a class itself.

In the example above, the output will simply be the string "Now I'm a class method!" However, using a similar declaration our class method can be more interactive.

Using our Futurama example from last week, let's write some simple class objects for some of the characters in the TV series.

So now we have 3 instance objects Fry, Zoidberg, and Bender, but let's say we wanted a way to determine how many of these character objects we have created and we wanted to print that value to the screen. In this case we are no longer working with one particular instance of the class, but with the class itself. Let's add a class method that counts how many times our Futurama class is instantiated.

First, we have to create a class variable @@count and set it equal to 0. Then we have to change the value of @@count by adding 1 to it each time initialize is called, which happens every time an object of the class is created. Lastly, we have to add a class method that allows access to the value of @@count when called outside the class. We this code is run in command line, 3 is printed as expected, since we have created 3 characters so far.

Blog Archive

Coming Soon!