Project Ramon

A learning journey from a Ruby noob perspective

Class vs Instance Methods in Ruby

class_methods_header_img

What are class methods? They are methods available to be called on the Class, whereas instance methods are methods that are available to objects instantiated by the Class.

Heres one example of the differences in writing a class_method vs instance_method:

koans4_ex1

We called the first .chew method on the class Apple and the second .chew on the object fruit. The .chew methods are entirely different. One is .chew available only to the class Apple, and the second .chew method can only be called on objects instantiated by the class Apple.

One practical reason for defining class methods would be to receive an object count for a particular class. If we had the following:

We would always know how many book objects our class has created. We couldn’t call .talley on one instance/object of the Book class, because a .chew instance¬†method would only have knowledge within the scope within an instance of a book object. Many books would mean many different objects, so it makes sense for the class to oversee the counting of objects it has created.

There are different ways we can define class methods. Lets go over them and see which one(s) you prefer.

The first way to define class methods in the illustration above is my preferred way of doing so. This way I can still have my class inherit from a parent.

There is an additional way to call a class method, we can call a class method from the object like so:

We can call the .class method on our fruit object, by calling .class on our fruit object, .chew is now in the context of the Apple class and not accessing the .chew instance method.

Advertisements

Categories: AirPair, Newbie, Ruby

Tags: , ,

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