Ruby Classes

Why you should use Classes

February 14, 2015

In these blogs we have been talking about ruby but not really gone into great details on how Ruby works. To understand classes we have to first understand some basic workings of Ruby.

Ruby is an object oriented programming language. What this means is that Ruby programs are built using objects. That doesn't really tell us much. Let's think about this in different terms, let's think of Ruby as if it were like Legos. When we make a program in Ruby, it's like we are building something with Legos. Objects in Ruby would be like the bricks in legos. We can use different bricks to build our end product.

With Ruby and with Legos, we don't build our products only using one type of brick. No we use many bricks and they all have different characteristics, and functions. This is where classes come into play. Class can be assigned to an object and allow the user to manipulate what they want. Lets go back to the Lego analogy. Lets think of different sized bricks to be different classes. There can be a class of bricks that are thin but long, or we can get the tall ones that are squared. We can have different shapes classes, ones with holes in them, they also have ones shaped like tools/accessories. All of these bricks are objects that have been assign a specific class.

Objects and classes make up most of ruby. You have already seen some classes and probably didn't even know it. For instance, any whole numbers that you have seen we call integers. Guess what, they belong to the Integer class. The Integer class gives these numbers properties, and also defines the methods that can be used to manipulate them. In Ruby you can also create your own class. Below is an example of a class that I have made. It is a randomizer that picks who goes first for a game.

As you can see above, we define a class using class First_player. The first letter of a class needs to be capitalized. Also at the end of every class we use end to close everything inside it. Not shown is how you would call a class. One method of doing this is object = Class.new. The object is the variable name for the object, and Class is the class name (remember to capitalize).

As you can see, the inside look familiar. Inside of a class we basically can create variables and methods which we have been doing before. The methods we define here can not only be called on objects of the same class but in other methods in this class.

I don't want to confuse you or give you to much information at once, so I think this is a good stopping place for the blog. If you want more information, I would suggest looking here or looking at class terminalogy such as instance variable.