From: Jamis Buck Date: 2004-11-03T08:34:42+09:00 Subject: Re: Converting hash keys to symbols Florian Gross wrote: > Jamis Buck wrote: > >> Is there an elegant way of converting all of the keys of a hash to a >> symbol? The solution can assume that the existing keys are either >> strings or symbols. > > > Does this help? > > a = Hash.new do |hash, key| > hash.fetch(key.is_a?(Symbol) ? key.to_s : key.to_sym, nil) > end Clever! That's really nice. It won't quite work for me, however, since I don't have control over the creation of the hash that I'm receiving. >> Also, if a key is a string, it may contain a dash character which must >> be converted to an underscore. > > > Why? Symbols can contain dash characters. See :"foo-bar", %s{foo-bar}, > "foo-bar".intern and "foo-bar".to_sym. Yah, I know. But I like to use symbols so I don't *have* to type the quotes. :) It's a matter of convenience rather than optimization, in this case. Thanks for the suggestions, Florian. Thanks, especially, for pointing out #to_sym. I wasn't aware of that, and I like it better than the less-intuitive #intern. - Jamis -- Jamis Buck jgb3@email.byu.edu http://www.jamisbuck.org/jamis