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!

Hashes in Ruby

After class last night I went back to go over hashes in Ruby. What better place to work than McNally Jackson’s Bookstore! Yesterday was one of the first warm days so I took a nice long walk before settling down to work at this cute little bookstore. They have awesome coffee too which by the end of the day was a great treat!

photo

While I was at this beautiful coffee shop I learned about hashes in Ruby. Here is a little brief intro to hashes! (Click on the image to read about the willy_wonka hash)

wonka_bar