Michael Neumann
11/2/2004 9:53:00 PM
On Wed, Nov 03, 2004 at 06:35:59AM +0900, Jamis Buck wrote:
> Golf question...
>
> 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. Also, if a key is a string, it may contain a dash
> character which must be converted to an underscore.
>
> Something like this, only more elegant, would be nice:
>
> a = some_hash_of_strings_and_symbols
> new_a = Hash[*a.collect { |k,v|
> k = k.gsub(/-/,"_").intern if k.is_a?(String)
> [k,v] }.flatten]
>
> Any takers?
But you should not do this for random strings, as symbols are AFAIK not
GC'ed.
How about this (converts all symbols to strings, which is easier and
more secure, as strings get GC'ed):
h = Hash.new
a.each {|k,v| h[k.to_s.tr('-','_')] = v}
h
Regards,
Michael