Objects and Classes (brief)

This is going to be a high level post about classes, objects and scope. So in Ruby a class is where you create objects and objects become instances of that class. In makes more sense in terms of an analogy. If you think of a class as a classroom you have student objects that are instances within that classroom.

The students have relationships to one another they might be the same age or be the same height, same gender, but they are all unique. If I created this classroom of students (students class) I would define it in ruby like this;

class Students

Always first letter capitalized. To create a new object (or student object) in this class I would call the new method on Students and would store this in a variable.

student1 = Student.new
student2 = Student.new

notice: student1 is something totally different from Student.

Last post I talked about the initialize method, that method defines the parameters that you can pass when calling .new on a class. So you could have default height, gender, age any number of parameters set for a new student or you could define them specifically for that instance of your class.

If you haven’t seen already an important thing to note about classes is inheritance. Some programming languages do this different but in Ruby to inherit the behaviours from another class you just define it at the same time you are defining your class.

class Students variable
instance variable -> @variable
class variable -> @@variable
global variable -> $variable.

So when you are defining the variable it is important to remember to use the correct prefix based on where you want to use it. A class variable has to be initialized when you create them and that variable will then exists for all objects that are crated within that class. For example @@size_of_feet if created in the Students class would be available for each instance or object within the class. Similarly we could define a variable that would only be used in one instance of that class like @favorite_hockey_player just for the boys object in the students class.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s