From: sera@... (Francis Hwang) Date: 2003-05-20T11:50:16+09:00 Subject: Re: examples for my OSCON talk "Chris Pine" wrote in message news:<02b701c31c8d$c6b0fc40$6401a8c0@MELONBALLER>... > I know it's wrong to ask the mailing list for help on your homework, but > this isn't *really* homework... > > My talk is "Understanding Ruby's Object Model", but I'd like to start (and > maybe end) with some really cool examples about the cool things you can do > in Ruby relating to classes and modules being objects. Not sure if this counts as cool, but it was useful to me: I've programmed an object-relational mapping framework in Ruby where fields are stored as data structures, to be retrieved at runtime. They're class methods, so let's say you have a User class: class User < DomainObject def User.fields # return an array of Field objects end end .... so then you can have code like class ObjectCreator def verify (valueHash, aClass) # for each field defined for this domain object class, give it a chance to # throw an exception if there's an invalid value aClass.fields.each { |field| field.verify (valueHash[field.name]) } end end "aClass" in the code above is a metaclass: You don't pass in an instance, but the class itself. (You'd call "verify (valueHash, User)", not "verify (valueHash, johnDoe)".) The neat thing about this is that you can attach class-specific data and use it without knowing at runtime what class you're dealing with. You can't do this in Java without jumping through some really really nasty hoops: It binds class methods at compile-time. (Java class methods aren't really class methods at all; they're more like global methods that are bound to a particular namespace.) > Also, a question: what's the difference between a class's singleton class > and a metaclass? If I'm not mistaken, these are the same in Ruby, but I > mean conceptually: what is a metaclass? Traditionally a singleton is any class which is guaranteed to have only one instance. It's useful but also easy to trip over. (See http://c2.com/cgi/wiki?SingletonPattern for a big discussion of this.) Ruby also uses the word "singleton" to describe any instance whose methods have been explicitly set to vary from the standard class definition. For example: myStrangeArray = [ 0, 1, 2 ] def myStrangeArray.length 999 end (I don't know where this usage comes from or if it's unique to Ruby; it tripped me up when I first came across it.) Francis