hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Seeing Metaclasses Clearly #

by why in inspect

If you’re new to metaprogramming in Ruby and you’d like to start nursing a deep understanding for it, I’ve written a detailed article dissecting metaclasses. It’s all based on the following code, which I call Metaid.

 class Object
   # The hidden singleton lurks behind everyone
   def metaclass; class << self; self; end; end
   def meta_eval &blk; metaclass.instance_eval &blk; end

   # Adds methods to a metaclass
   def meta_def name, &blk
     meta_eval { define_method name, &blk }
   end

   # Defines an instance method within a class
   def class_def name, &blk
     class_eval { define_method name, &blk }
   end
 end

The article contains a lot of stuff I excluded from chapter six of my cartoon Ruby book because it was just getting too specific for the common reader.

Update: Thanks to feedback from Ruby-Talk and sundry readers out there, the article is proofread and errors are being fixed. Certainly post here in the comments if you have further.

said on 18 Apr 2005 at 10:05

Awesome. This is what I was reaching for with my earlier Dwemthy’s array hackery, but I just didn’t have the vision.

I’d be very happy if metaid became part of the ruby core in some fashion.

(Pedant that I am, I’d prefer the more verbose and consistent singleton_class, singleton_class_eval, define_singleton_method, and define_class_method in place of metaclass, meta_eval, meta_def, and class_def. But I cannot speak for others.)

said on 18 Apr 2005 at 11:35

I may change the names. It’s confusing to people who read the article and then read class.c. But I hate to use a name other than metaclass because I like it so.

said on 18 Apr 2005 at 12:15

I think Matz’s choice of singleton class is more suggestive of what’s actually going on—these are the grubby one-off classes depending from the bottom of the class hierarchy, rather than those “meta” classes hovering above it all, transcendant-like.

I wish that weren’t the case, because metaclass is so mellifluous, whereas singleton class is so not.

said on 18 Apr 2005 at 19:40

Excellent! This entry should be prized MVP of the first half of the year.

said on 19 Apr 2005 at 14:20

I never meta class I didn’t like.

Comments are closed for this entry.