From: Florian Gross Date: 2004-11-03T08:08:48+09:00 Subject: Re: Converting hash keys to symbols 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 a["one"] = "eins" a[:two] = "zwei" a["one"] == a[:one] # => true a["two"] == a[:two] # => true > 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. Also note that #to_sym is defined for Symbol as well. So maybe you could also do something like this (in case the above doesn't work for you): result = Hash.new(&a.default_proc) until a.empty? key, value = *a.shift result[key.to_sym] = value end a.replace(result)