Search code examples
rubyclassmetaclasseigenclass

About class definition in Ruby


Recently, I was investigating into some details about classes in Ruby, and was confused by class definition.

In Ruby, the class definition is as follows,

class A
    def self.my_method
    end
end

and it's the same as

class A
    class << self
        def my_method
        end
    end
end

then I was confused. For the 1st case, self can be regarded as a pointer to currently using object, and current class of the context is A. And the method looking-up is done recursively. But my question is, what does def do? How does it change the current object and context? The problem is same for the 2nd case. How does the description like class << self change the current object and context?

And another question. As far as I know, all Class objects are obeying design patterns like fly-weight, since they share the same Class object with same definition. Then the eigenclass became confusing. Since the def in a eigenclass actually defines a method with Class object, how can it be related to "def self.*"?

It looks too complicated from the outside, and I may need the design details of Ruby.


Solution

  • class A
      # self here is A
      def aa
        # self here is the instance of A who called this method
      end
      class << self
        # self is the eigenclass of A, a pseudo-class to store methods to a object.
        # Any object can have an eigenclass.
        def aa
          # self is the pseudo-instance of the eigenclass, self is A.
        end
      end
    end
    

    This is the same:

    class A
      def self.aa
      end
    end
    

    And this:

    class << A
      def aa
      end
    end
    

    And also this:

    def A.aa
    end
    

    You can open the eigenclass of anything:

    hello = "hello"
    class << hello
      def world
        self << " world"
      end
    end
    hello.world #=> "hello world"
    "my".world  #=> NoMethodError
    

    An eigenclass is actually an instance of Class, it has it own eigenclass too.

    "If it appears to be too confusing, just remember that Class is an object and that Object is a class."