0

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
abc123
  • 8,043
  • 7
  • 49
  • 80
  • possible duplicate of [class << self vs self.method with Ruby: what's better?](http://stackoverflow.com/questions/10964081/class-self-vs-self-method-with-ruby-whats-better) – toro2k Oct 08 '14 at 15:05
  • The question is a duplicate, but the answers on that question definitely leave something to be desired. – Max Oct 08 '14 at 16:03

1 Answers1

2

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.

Max
  • 15,157
  • 17
  • 82
  • 127
  • Good explanation, Max. One small thing. I've often seen the expression "open a class", though I've never found a definition for that. Isn't more accurate to say that `class << self` causes `self` to be changed to the singleton class? – Cary Swoveland Oct 08 '14 at 16:47
  • "I've often seen the expression "open a class", though I've never found a definition for that." <-- `open a class` simply means do something to a.k.a modify the class. – weakish Apr 29 '15 at 01:44
  • The reason it is refereed to as "opening the class" is because everything in between `class << self` and the corresponding `end` modifies the class. Thus, the class is "open" between `class << self` and `end`. – Max Apr 30 '15 at 21:38