why are metaclasses created in ruby?

后端 未结 4 1888
醉酒成梦
醉酒成梦 2021-02-08 11:43

I m trying to understand the Ruby Object Model. I understood that the instance methods are saved in the class rather than in the objects of the class because it removes redundan

4条回答
  •  悲哀的现实
    2021-02-08 12:00

    This isn't quite an answer to your question, but it might be useful. Two things to think about that might help:

    • metaclass is not really a good name for what's going on here when you think of how the meta prefix is used in other scenarios. eigenclass which you will see used in other documentation is probably a better name, meaning "an object's own class"
    • It's not just classes that have an eigenclass, every object does

    The eigenclass is used to store methods that are specific to a particular object. e.g. we can add a method to a single String object:

    my_string = 'Example'
    def my_string.example_method
      puts "Just an example"
    end
    

    This method can only be called on my_string and not on any other String object. We can see that it is stored in my_string's eigenclass:

    eigenclass = class << my_string; self; end # get hold of my_string's eigenclass
    eigenclass.instance_methods(false) # => [:example_method]
    

    Remembering that classes are objects, in this context, it makes sense that the methods specific to a particular class should be stored in that class's eigenclass.


    Update: actually, there is an eigenclass for the eigenclass. We can see this more easily if we add eigenclass as a method to Object:

    class Object 
      def eigenclass 
        class << self
          self
        end 
      end 
    end
    

    and then we can do:

    irb(main):049:0> my_string.eigenclass
    => #>
    irb(main):050:0> my_string.eigenclass.eigenclass
    => #>>
    irb(main):051:0> my_string.eigenclass.eigenclass.eigenclass # etc!
    => #>>>
    

    whilst this seemingly creates an infinite regress, this is avoided because Ruby only creates the eigenclasses on as they are needed. I think the name "metaclass" really is a source of part your confusion because you are expecting a "metaclass" to hold some kind of information that it actually doesn't.

提交回复
热议问题