Class Methods

In this chapter, we will answer the question: Where does the class methods live?

Instance Method

Let's define an instance method drive() in Car class.

class Car
  def drive
    p 'driving'
  end
end

p Car.instance_methods(false).sort

This prints:

[:drive]

There is no surprise here, if we define an instance method, it shows up in the output.

Class Method

What if we had defined a class method drive() instead?

class Car
  def self.drive
    p 'driving'
  end
end

p Car.instance_methods(false).sort

This prints:

[]

This is because there are no instance methods in Car. There is class method drive(). The question is where does the class methods like drive() live?

The Singleton Class

The class methods live in singleton class. We can use a special syntax that gives us a reference to the singleton class as follows:

class Car
  def self.drive
    p 'driving'
  end
end

singleton_class = class << Car
  self
end

p singleton_class.instance_methods(false).sort

This prints:

[:drive]

We can see that the singleton class holds the class method we have defined in the Car class. Ruby 1.9 introduced singleton_methods that is an alternative to class << syntax. We can use it like this:

p Car.singleton_methods

This prints:

[:drive]

Different Ways to Define Class Method

To illustrate the point made above, we can define the class method for Car in it's singleton like this:

class Car
end

class << Car
  def drive
    'driving'
  end
end

p Car.drive

This is same as this:

class Car
  def self.drive
    'driving'
  end
end

p Car.drive

And so is this:

class Car
  class << self
    def drive
      'driving'
    end
  end
end

p Car.drive

The last form of defining a class method will lead to difficulty in maintenance. Because it is difficult to determine whether it is an instance method or a class method. This happens when the class methods are way down below its class << self declaration.

Summary

In this chapter, we designed experiments to answer the question: Where does the class method live? We found that they live in singleton class.

results matching ""

    No results matching ""