Dissecting Ruby Classes
11/26/2015
Classes, Instance Variables, and Instance Methods
Classes are blueprints for objects. With this blueprint your program can then create multiple instances of an object. Within classes are two primary pieces of information: attributes and behaviors. They are commanly referred to as instance variables and instance methods. They both contain information that is unqiue to each instance.
Original Source: Head First Ruby
Thinking of Classes in Terms of the Real World
The easiest way to wrap your mind around this concept is to compare it to the real world. Let's use cars as an example. All cars have basic characteristics and behaviors in common: Characteristics: wheels, doors, windows, trunk, headlights, colors, etc. Behaviors: drive, park, blow horn, etc. There are several different types of cars that exist. These different types of cars can be thought of as instances of the class car. Each type of car such as a Honda, Kia, Toyota, etc. all have characteristics that are distinct to them. In order to keep track of these distinct characteristics you store them in an instance variables. Instance methods can then utilize these instance variables to personalize object behavior. For instance, lets say you have a miles per hour instance variable that your instance method drive uses. Passing this instance method to drive will cause the method to perform differently for a Corvette vs. a Honda.
How do I Get Information about my Attributes?
In the previous example we only created writer methods which set or reset attribute values for instance variables. If you want to access the info stored in these variables you can create reader methods. These methods primary purpose is to return the values of instance variables.
Attribute Methods
If you have several reader and writer methods within your class it can make it very long. Ruby provides you with attr_* methods that allow you to create one line reader, writer, or accessor methods. The accessor method creates both a reader and writer method for a instance variable. *WARNING* while the attr_accessor method is very tempting to use, it's important to think about whether you want other classes to have access to your instance variables. If you are unsure it's best to not do it. Unnecessarily exposing your instance variables to other programs can change your instance variable values in unexpected ways.
Creating New Instances of Objects
Now that we have finished creating the car blueprint we can go ahead and create a instance of that object. You can either initialize a new instance object with certain attribute values, or you set them later via writer methods. Once you have a new instance created you can then use the variable name as a receiver object, and call methods on that object.