Anonymous Classes in Ruby

I’m currently watching Dave Thomas’ ‘Ruby Meta-Programming’ screencast from PragProg and he just said something that sorta blew my mind. It both made sense and I hadn’t quite realized that Ruby works this way.

Let’s say you declare a string:

person = "Jennifer"

Then I can also create a method only on person:

def person.job

And then when I call person.job, it returns ‘programmer’. Pretty cool, right? Apparently Ruby does this by creating an anonymous class. So when I’m looking for methods on person (which is a String), it first checks this anonymous class, then the String class, then Object, then BasicObject. I’m not quite sure of a real-life use case for this, but the idea is pretty neat.


Even cooler: if I define another method (say person.hobby), that will be put into the same anonymous class as person.job. Ruby will not create a new anonymous class for each singleton method; it knows that they should be part of the same class.