Ruby metaclass madness

Posted by t6d on Stack Overflow See other posts from Stack Overflow or by t6d
Published on 2010-03-15T10:38:24Z Indexed on 2010/03/15 10:39 UTC
Read the original article Hit count: 478

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.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about metaclass