Classes in Ruby

coffee

I spent today learning about classes in Ruby! With a little bit of coffee and a lot of reading I feel that I am starting to understand more about classes in Ruby. What is a class and why are they useful in Ruby? Here is a little bit of information on how to create a class:

heading_blog_shapes

 

I have all these shapes and I want them to be in the same class. So let’s make “Shape” class:

shape_class1

 

We created a class by writing “class” and then the name of the class which is “Shape”. Let’s “initialize” our Shape class so that it will do something.

shapes_class2

Now we added a method inside of our Shape class. The method has a very special name though…“initialize” can be thought of like an “on switch” for your class. Then you see two arguments for the method, which are “name, color”. Inside our method you will see “@name” and “@color” again, but why? Good question. These are know as “INSTANCE VARIABLES”. Let’s keep going and see why we need instance variables.

What’s going on now?! There is another method inside our Shape class. We added a method called “description” and notice that it has those “INSTANCE VARIABLES” again. We are going to use those variables from that first method and use it another method…and we are allowed to do that because they are special kinds of variables. You can tell that these are special variables, because they have the @ in front of them. OK, we have all this information, now what? Let’s “initialize” an instance of this class! (Get use to those words…initialize and instance.)

shape_class4

More code! OK…now we are creating instances of the class “Shape” and assigning them to variables. For example “square” is an instance of “Shape”. Now this is all great, but we aren’t printing anything to the screen yet. Our “puts” is tucked away inside that “description” method. How will anyone see all this awesome stuff?! Let’s add the last piece to this class puzzle.

shapes_class5

 

And now you will have the following printed out!

Leave a comment