Introducing Classes

Classes are designed to perform a functionality by themselves. This functionality can be, and usually is part of a larger group of functions which we would call a program.

For this example I made a simple standalone class and I will guide you through it's design and function.

Video Game Class

I wish I had this class when I went to school, but now I created it myself. First of all, you can view the complete code on my GitHub page right here.

Creating a class in Ruby is very straightforward. We simply declare the class. In order to use it we must define a method to initialize the class and the parameter it requires, in this case, we would like to know the title of the video game.

  class VideoGame
    def initialize(title)
      @title = title

Then we can declare an instance variable @title. You can see this is an instance variable because it has a single @ in front of the variable name. This means it can be used outside of this function and inside other functions which will be an instance of this same class.

This is best shown through a direct example:

  irb:> Skyrim ="Skyrim")
  => #<VideoGame:0x007f650ccc57e0 @title="Skyrim">;
  irb:> Skyrim.class
  => VideoGame
  irb:> Skyrim.class.superclass

In the first line I created a new instance of the class VideoGame by calling the new method and providing the title. This initializes the instance Skyrim, which exists separate, but inherits all properties of the VideoGame class.

Now we can do all sorts of things. I added a method so we can "play" the game as well to "quit" it when we've had enough, or have others things to do. (Like coding.)

  => "You start playing Skyrim. 10 hours pass. What? It's 2 am already? My morning self is gonna regret this."
  irb:> Skyrim.quit
  => "That's enough Skyrim for now."

The reason I could call title from the first method in my two other methods is because I made it an instance variable. Otherwise I would have seen an error message instead of all this fancy stuff resembling real life experiences.