Classes in Ruby
This is probably the 3rd or 4th attempt at classes in Ruby for me. With each pass at the concept, I try to get a little deeper and more understanding of the how and why.
The purpose of a class is to do a specific task or function. My mentor, Jeremy Friesen, sent me a link to his blog post about instance variables and caller methods which helped me to understand these concepts a bit better. If your class is a playing card, for example, you can build a bigger thing or concept or object with attributes and functionality through the use of a class and multiple methods within the class. I followed along (for the 2nd time) with theFirehoseProject’s videos on Object Oriented Programming (OOP) and did git commits of each step. Building a card class with 2 main attributes of suit and rank is a simple way to understand some of the things you can do with a class.
Here are the main things I learned:
- what you do inside the class stays there by default, you cannot view or change without adding that functionality first
- attr_reader and attr_writer add the ability for you (or anyone) to read and make changes to instance variables inside the class from outside the class
- attr_accessor is the refactored form of attr_reader and attr_writer
- you can build class level methods and regular methods inside the class
- the ability and preference to call “self”, both in regular methods and class methods, gives code longevity and less maintenance over time
I still don’t quite grasp how to implement “self” for methods without looking at a refactored example, but I definitely made progress. I feel ready for some more coding challenges and algorithms…