kodama
January 2, 2008, 12:26am
1
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?
E.g. I’d like to do something like this:
my_hash = YAML.load_file(‘my_file.yml’)
=> { ‘one’ => 1, ‘two’ => 2, ‘three’ => 3 }
my_hash.super_cool_hash_key_string_to_sym_transformation #one line of
code?
…
my_hash
=> { :one => 1, :two => 2, :three => 3 }
Please display your ninja skills. : )
Thanks,
kodama
kodama
January 2, 2008, 12:46am
2
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?
kodama
January 2, 2008, 12:53am
3
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 R. wrote:
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?
kodama
January 2, 2008, 12:59am
4
On Wed, Jan 02, 2008 at 08:26:31AM +0900, Old E. wrote:
code?
…
my_hash
=> { :one => 1, :two => 2, :three => 3 }
Please display your ninja skills. : )
class Hash
def symbolize_keys
replace(inject({}) { |h,(k,v)| h[k.to_sym] = v; h })
end
end
Thanks,
kodama
–Greg
kodama
January 2, 2008, 1:29am
5
Thank you both for your answers. It’s threads like these that make me so
so so happy to be programming with Ruby.
kodama
January 2, 2008, 3:28am
6
FYI, if you prefer, there is also ‘facets’ gem which has what you want.
You can selectively require parts of it. I think it’s
facets/hash_keyize.
http://facets.rubyforge.org/index.html
-andre
kodama
January 2, 2008, 1:13am
7
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.
kodama
January 2, 2008, 1:51pm
8
On Jan 1, 9:28 pm, Andreas S [email protected] wrote:
FYI, if you prefer, there is also ‘facets’ gem which has what you want. You can selectively require parts of it. I think it’s facets/hash_keyize.
You’re right, but that is the old library. Instead use Hash#rekey
require ‘facets/hash/rekey’
{“a”=>1}.rekey #=> {:a=>1}
{:a=>1}.rekey(&:to_s) #=> {“a”=>1}
{“a”=>1}.rekey{|k| k.capitalize} #=> {“A”=>1}
T.