Wednesday, May 23, 2007

The Other Side of the MethodicHash

It surprised me a little. Is my tendency to complete finally starting to disappear, lost to the quick turn-around time of agile - the build-only-what-you-need mentality?

When I looked over the MethodicHash, I missed a simple addition. I should have done the assignment side as well. Since I wasn't using it, I didn't write it. But now in retrospect, for completeness:
  class MethodicHash < Hash

def method_missing(method,*args)
string = method.to_s
if string[string.length-1,1] == '='
self[string[0,string.length-1].to_sym] = args[0]
else
self[method]
end
end

end
That's better. Now I can put things into and take things out of the hash with a syntax that looks like I'm reading and writing an attribute.

By the way, this doesn't work for all strings and symbols. Yes, you guessed it - the ones that match the method names of a Hash can't be used. But that's a fairly small set and the class should still do what I need it to do.

No comments: