Tuesday, May 22, 2007

The MethodicHash Class

Ruby is just a delight to work with. I really need to write a book about how easy it is to create new dialectic constructs that improve the way you can write your code using the language. Once upon a time I was chided for the heavy use of macros in my C and C++ code; in Ruby, you can build the language structures dynamically and it just feels so good!

Today I put together a little magic on the Ruby Hash that lets me write really nice DSL extensions. Calling it MethodicHash, I extended the lookup of a value using a key, and added a method_missing to do a lookup with the name of the missing method as a key:
  class MethodicHash < Hash

def [](key)
begin
super(key) || super(key.to_s) || super(key.to_sym)
rescue
nil
end
end

def method_missing(method,*args)
self[method]
end

end
It might not look like much, but when you've embedded a DSL into your code with a require and you've backed it with a MethodicHash, you can say things like
  foo.bar
instead of
  foo['bar']
or
  foo[:bar]
making the code ever so much more readable. Hiding coding details like this so simply and easily is one of Ruby's greatest benefits to the programmer.

The MethodicHash is a jumping-off point to more complex dynamics that I'll be hiding under the surface. More will definitely be coming.

No comments: