Class Methods versus Instance Methods in Ruby

Daniel Kim
3 min readApr 21, 2021

A class method in Ruby, is a method that refers to the entirety of a class. An instance method is a method that refers to a specific instance of a class.

Let’s look at a couple examples.

Assume that we have three models: Actor, Movie, and Role. The relationships between these models is that a role belongs to an actor and a movie, a movie has many roles and actors through roles, and an actor has many roles and movies through roles.

Shown below is an example of a class method.

In this example, we are in the Actor model and trying to return the instance of Actor that has the highest total salary for all their roles. As you can see, we are using the “self” keyword to indicate that this is a class method and is referring to the Actor class itself. This means that we are looking at every instance of the class that we are currently in. So “self” being the class, we are looking at all of the instances, then sorting by the sum of salaries for the total roles for each instance (a representing each actor). Then we are returning the last instance in our newly ordered array of actors, because the sort_by method will default into ascending order.

Now let’s take a look at an instance method.

In this example, we are creating a role that will be associated with an instance of Actor. So this method must be called on a specific instance such as our first Actor. So if we try to call it on the entire class with Actor.cast_role, we will get a NoMethodError. Instead we must do Actor.first.cast_role and fill out the parameters.

You may see this example of an instance method and wonder why it isn’t a class method even though it contains the “self” keyword. In this example, we are trying to return a collection of all the movies that an instance of actor performed in, where the the box office earnings for those movies are greater than $50,000,000. The word “self” in this case represents the instance you are calling the method on. So if you were trying to call the method blockbusters on the first Actor, self.movies.where(“box_office_earnings > 50000000”) is the same as Actor.first.movies.where(“box_office_earnings > 50000000”).

In conclusion, class methods must be called on classes and instance methods must be called on instances of classes.

Thanks for reading!

Resources

--

--