From: "David A. Black" Date: 2005-08-26T21:50:45+09:00 Subject: Re: symbols vs. strings Hi -- On Fri, 26 Aug 2005, Mark Volkmann wrote: > I got the impression that when a method expects a Hash containing > certain keys, I can generally specify the keys using either Symbol or > String objects. So I tried this. > > h = {} > h[:foo] = 19 > h['foo'] = 20 > > and was surprised to see that those are treated as distinct entries > in the Hash. > > So how is it that I can sometimes choose whether I want to specify a > given key as either a Symbol or a String? You can hook into the [] and []= methods. Here's one way: module SSHash def []=(k,v) super(k.to_s,v) end def [](k) super(k.to_s) end end h = {}.extend(SSHash) h[:a] = 1 h["b"] = 2 p h["a"] # 1 p h[:b] # 2 (Note that redefining [] and []= does not affect other get/set methods, like fetch.) David -- David A. Black dblack@wobblini.net