Hello Rubyists,
When dealing with hashes, I like using symbols for key names instead of
strings. Is there an easy way to convert hash keys from symbols into
strings?
class Hash
def super_cool_hash_key_string_to_sym_transformation
self.each_key{|k| k = k.to_sym}
self
end
end
-or-
my_hash.each_key{|k| k = k.to_sym}
Either of these work for you?
···
On Jan 1, 2008, at 3:26 PM, Old Echo wrote:
Hello Rubyists,
When dealing with hashes, I like using symbols for key names instead of
strings. Is there an easy way to convert hash keys from symbols into
strings?
Hello Rubyists,
When dealing with hashes, I like using symbols for key names instead of
strings. Is there an easy way to convert hash keys from symbols into
strings?
Hi Steve,
Thanks for your quick response, but I'm afraid that didn't do the trick.
It looks like the block just completes without actually changing
anything, or at least it doesn't transform what needs to be transformed.
Do you have any other suggestions?
Steve Ross wrote:
···
class Hash
def super_cool_hash_key_string_to_sym_transformation
self.each_key{|k| k = k.to_sym}
self
end
end
Sorry. Look at Greg's for the keen Ruby way to do it. There should be a symmetric stringify_keys for consistency as well.
My hash works as such:
class Hash
def symbolize_keys
t = self.dup
self.clear
t.each_pair{|k, v| self[k.to_sym] = v}
self
end
end
h = {'one' => 1, 'two' => 2}
puts h.symbolize_keys.inspect
{:one=>1, :two=>2}
Again, Greg's is cooler.
···
On Jan 1, 2008, at 3:53 PM, Old Echo wrote:
Hi Steve,
Thanks for your quick response, but I'm afraid that didn't do the trick.
It looks like the block just completes without actually changing
anything, or at least it doesn't transform what needs to be transformed.
Do you have any other suggestions?
Steve Ross wrote:
class Hash
def super_cool_hash_key_string_to_sym_transformation
self.each_key{|k| k = k.to_sym}
self
end
end
Date: Wed, 2 Jan 2008 09:29:11 +0900
From: kodama@bluexpanse.net
Subject: Re: transform hash key from string into symbol
To: ruby-talk@ruby-lang.org
Thank you both for your answers. It's threads like these that make me so
so so happy to be programming with Ruby.
--
Posted via http://www.ruby-forum.com/\.