Tuesday, February 19, 2008

Unexpected Hash Behavior With String Keys

I was looking for a way to create a case-insensitive Hash class. One suggestion was to use NormalizedHash (http://pastie.caboo.se/154304), and override methods on the String keys. This doesn't work as expected.

I found that Hash makes a duplicate of the String key. This unfortunately removes any methods added in the singleton class. (surprise!)

Here is the code to demonstrate this behavior: http://pastie.caboo.se/154595


Shortly after writing the above post, I came across a little footnote in Hash#[]= which says... "(a String passed as a key will be duplicated and frozen)"

I learn something new every day. (I wish this information was given in the class description instead of the method description where it is easly missed.)