loading...

Ruby: class methods vs. instance methods

adamlombard profile image Adam Lombard ・1 min read

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class.

Consider the following Ruby class:

class SayHello
  def self.from_the_class
    "Hello, from a class method"
  end

  def from_an_instance
    "Hello, from an instance method"
  end
end

This would yield the following:

>> SayHello.from_the_class
=> "Hello, from a class method"

>> SayHello.from_an_instance
=> undefined method `from_an_instance' for SayHello:Class


>> hello = SayHello.new
>> hello.from_the_class
=> undefined method `from_the_class' for #<SayHello:0x0000557920dac930>

>> hello.from_an_instance
=> "Hello, from an instance method"

We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.

Railstips has a nice article with more detail and a discussion of alternative ways of creating both class methods and instance methods.

Posted on by:

Discussion

markdown guide
 

The nice thing about Ruby's object model is that class methods are really nothing special: SayHello itself is an instance of class Class and from_the_class is a singleton method defined on this instance (as opposed to instance methods of Class that all instances share):

SayHello.singleton_methods
#=> [:from_the_class]

Conceptually this is the same as defining a singleton method on any other object:

s = 'dev.to'

def s.yell
  'DEV.TO'
end

s.yell
#=> "DEV.TO"

s.singleton_methods
#=> [:yell]

# alternatively
# class << s
#   def s.yell
#     'DEV.TO'
#   end
# end
 

Thanks for the deeper dive on that, Michael!