Class vs. Instance Methods in Ruby

Zach Weber
2 min readJul 22, 2020

--

In Ruby classes there are two main types of methods: class and instance. These methods perform different tasks. At this point you may be asking yourself, “What is a Ruby class and what does it do?” If that’s the case, here’s a review.

Classes are a grouping of methods that exist to construct an object by creating a new instance of the class. Instances are the objects created by a class. Class methods are called on the class itself (hence why in the method declaration, it will always state def self.class_method_name), whereas instance methods are called on a particular instance of the class (these are declared like regular methods: def instance_method_name).

Due to the duties of these methods being separate, they can’t perform the other’s task, meaning that you wouldn’t call a class method on an instance of the class and you wouldn’t call an instance method on the class. As with many things in programming, examples can be better than descriptions, so let’s dive in:

class Example  def self.class_method
puts "I am a class method"
end
def instance_method
puts "I am an instance method"
end
end//Example.class_method => "I am a class method"
Example.instance_method => undefined method `instance' for Example:Class
Example.new.instance_method => "I am an instance method"
Example.new.class_method => undefined method `class_method' for #<Example:0x0000558d5023c390>

As you can see, when Example.class_method was called, it returned the puts statement in the method because it was called on the class itself. When Example.instance_method was called, it returned as undefined because there was no instance of the class specified to call the method on. In the second group of examples, a new instance of the class was created (Example.new), so the opposite occurred.

Key takeaways

  • Class methods can only be called on classes
  • Instance methods can only be called on instances of classes
  • Class methods are always defined def self.method_name
  • Instance methods are always defined def method_name

Happy coding!

--

--

Zach Weber

Denver-based Software Engineer, nature lover, and lifelong learner