why are metaclasses created in ruby?

后端 未结 4 1881
醉酒成梦
醉酒成梦 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:06

    The reason really boils down to what self is. For any given method, self is an instance of the object that the method is defined one.

    In an instance method, stored on MyClass, self will be the instance of MyClass that you called #hi from. In a class method, self will be the instance of the metaclass (that is, the class itself). Doing it with the metaclass means that the concept of self is unchanged, even when operating on a class, which is itself just a singleton instance of its metaclass.

提交回复
热议问题