On 2/11/08, J. Cooper <nefigah / gmail.com> wrote:
> I ran into something I hadn't realized (common occurrence). Keying a
> hash with a symbol is not the same as using a string. I guess it makes
> sense, but I've seen it done both ways, and I had been always using
> symbols for my keys. But then I ran into an issue on loading an external
> YAML object into a hash, and didn't realize it was keyed with strings so
> I got errors the first time around.
>
> So two questions:
> 1) What is the preferred method of keying hashes? Symbols, strings,
> other?

   Symbol keys
         +    :a is one less keystroke than "a"
         +? performance of Hash with symbol keys MIGHT be slightly
faster, but probably insignificant.
         -    More symbols get interned which can't get garbage
collected, even after the hash is.

   String keys

        + keys can be GCed when removed from hash, or when the hash is GCed.

> 2) Is there a smooth way to handle hashes that may have been keyed in
> either fashion?

Rails is probably most responsible for popularizing symbol keys.
ActiveSupport implements a HashWithIndifferentAccess which can use
either symbols or strings interchangeably in access methods.
Internally it uses string keys.


-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/