abc123
abc123

Reputation: 8303

In Ruby, what is the difference between a class method and a class's singleton method?

I've seen this in code before and I just read about it in The Well Grounded Rubyist by David A. Black, but there are no examples of use cases to help me understand why someone would want to define a singleton method on a class like this:

class Vehicle
    class << self
        def all_makes
            # some code here
        end
    end
end

How is the above singleton method on a class different than the usual class method like this:

class Vehicle
    def self.all_makes
        # some code here
    end
end

Upvotes: 0

Views: 103

Answers (1)

Max
Max

Reputation: 15975

Yehuda Katz made an excellent writeup of the differences (among other things). You can find that here.

To give you a short summary. When you are defining the class, the self keyword refers to the class itself. So, when you do self.method you are defining a new method on the Person class. Every class has a metaclass, also known as the singleton class, which can be accessed and modified. In the case of class << self you are opening up the singleton class and modifying that value. Functionally, the result is the same, but the class being modified is different.

Upvotes: 2

Related Questions