Ruby metaclass madness
- by t6d
I'm stuck. I'm trying to dynamically define a class method and I can't wrap my head around the ruby metaclass model. Consider the following class:
class Example
  def self.meta; (class << self; self; end); end
  def self.class_instance; self; end
end
Example.class_instance.class # => Class
Example.meta.class           # => Class
Example.class_instance  == Example      # => true
Example.class_instance  == Example.meta # => false
Obviously both methods return an instance of Class. But these two instances 
are not the same. They also have different ancestors:
Example.meta.ancestors            # => [Class, Module, Object, Kernel]
Example.class_instance.ancestors  # => [Example, Object, Kernel]
Whats the point in making a difference between the metaclass and the class instance?
I figured out, that I can send :define_method to the metaclass to dynamically define a method, but if I try to send it to the class instance it won't work. At least I could solve my problem, but I still want to understand why it is working this way.