KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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] What's 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. Update Mar 15, 2010 13:40 Are the following assumptions correct. If I have an instance method which calls self.instance_eval and defines a method, it will only affect the particular instance of that class. If I have an instance method which calls self.class.instance_eval (which would be the same as calling class_eval) and defines a method it will affect all instances of that particular class resulting in a new instance method. If I have a class method which calls instance_eval and defines a method it will result in a new instance method for all instances. If I have a class method which calls instance_eval on the meta/eigen class and defines a method it will result in a class method. I think it starts to make sense to me. It would certainly limit your po
Tags (comma-separated)
Save Edits
Cancel