DEV Community

Andrea Esparza
Andrea Esparza

Posted on

Instance vs Class Methods in Ruby

The term "self" in Ruby was one of the toughest things to wrap my head around. There are times when "self" refers to a class and there are times when "self" refers to an instance of that class, which affects the way we write methods.

Classes and Instances

To understand instance and class methods, let's first dissect what instances and classes actually are. A class, essentially, is a collection of instances. If we think about it along with the database, the class represents the overall table and the instances represent each row of that table.

Instance vs Class Methods

Now that we understand how instances and classes are related, we can talk about methods. Methods are what we use to manipulate and extrapolate details from our database. We can create methods to find, sort, delete, and so much more. The million dollar question becomes "do we want our method to affect the class as a whole, or do we want our method to affect each instance?"

Class Methods

If we want our method to affect our class as a whole, then we need to write a class method. Class methods are usually presented with a period, such as ClassName.method_name. This let's us know that our "self" is the class, so our code would look something like this:

class ClassName
   def self.method_name
      ClassName.method
   end
end
Enter fullscreen mode Exit fullscreen mode

Instance Methods

If we want our method to affect each instance of the class, then we need to write an instance method. Instance methods are usually presented with a hashtag, such as ClassName#method_name. This let's us know that our "self" is the instance, so our code would look something like this:

class ClassName
   def method_name
      self.method
   end
end
Enter fullscreen mode Exit fullscreen mode

Umm, okay but I'm still confused

If you're still feeling like this "self" thing is daunting, I recommend using a console to test things out. At Flatiron, we've been encouraged to start a pry session to test our methods out in the console. For class methods, we type ClassName.method_name. For instance methods, we need to think of a specific instance to test. One built in case is the "first" instance. That would be the first row of the table. So when testing methods in the console, we can type ClassName.first.method_name.

Conclusion

I'll leave you with something that I've repeated to myself many times: class methods affect the whole class, a.k.a. the whole table; instance methods affect an instance of the class, a.k.a. a row of the table.

Top comments (0)