DEV Community

Cover image for Instance Methods vs. Class Methods: What's the Difference?

Posted on

Instance Methods vs. Class Methods: What's the Difference?

If you are starting your journey to becoming a software engineer, you will be introduced to Ruby at some point. If you find yourself struggling to differentiate between instances and class methods, this blog will hopefully help shed some light on the key differences between the two.

Fist, let me explain what a class is. Ruby is an object-oriented programming language, right? A class is a blueprint from which objects, or instances are created. For example, if you had a class called MLB_team (MLB = Major League Baseball), each MLB team would be an instance of that class. Here is a diagram to assist:

Image description

Each instance, or team would have their own set of data depending on what columns are set up in the table - a topic for a different day. Some column examples might look like this:

MLB_team instance -> team_name, team_manager, team_location, total_wins, total_losses, stadium_capacity, world_series_wins, world_series_losses, etc...

Now that we know what instances and classes are, now let me explain what methods are. A method is a set of expressions that return a value, very similar to a function in JavaScript.

The first key difference - syntax. Instance methods are called on the instances. Class methods are called on the class and declared using the "self" keyword, seen below.

Image description

Instance methods can be used to add, update and display information corresponding to the specific instance, whereas class methods can be used to query select information from all of the instances in the class.

In short, class methods are big-picture, looking at all the data in the class - every instance included. Instance methods are more specific, only looking at the specific instance.

Top comments (0)