如何转换Ruby哈希以使其所有键都是符号? [英] How do I convert a Ruby hash so that all of its keys are symbols?
问题描述
{id=> 123,name=> test}
我想将它转换为:
{:id => 123,:name => test}
hash = {apple=> 香蕉,椰子=> domino}
Hash [hash.map {| k,v | [k.to_sym,v]}]
#=> {:apple =>banana,:coconut =>domino}
更新: @mu太短:没有看到递归一词,但是如果你坚持(同时保护不存在 I have a Ruby hash which looks like: I would like to convert it to:
Update: @mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent
这篇关于如何转换Ruby哈希以使其所有键都是符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
to_sym
,只是想提醒一下,在Ruby 1.8中 1.to_sym == nil
,所以玩一些关键类型可以误导):
hash = {a=> {b=> c},d=> e,Object.new => g}
s2s =
lambda do | h |
哈希=== h?
Hash [
h.map do | k,v |
[k.respond_to?(:to_sym)? k.to_sym:k,s2s [v]]
end
]:h
end
s2s [hash]#=> {:d =>e,#<对象:0x100396ee8> =>g,:a => {:b =>c}}
{ "id" => "123", "name" => "test" }
{ :id => "123", :name => "test" }
hash = {"apple" => "banana", "coconut" => "domino"}
Hash[hash.map{ |k, v| [k.to_sym, v] }]
#=> {:apple=>"banana", :coconut=>"domino"}
to_sym
, just want to remind that in Ruby 1.8 1.to_sym == nil
, so playing with some key types can be misleading):hash = {"a" => {"b" => "c"}, "d" => "e", Object.new => "g"}
s2s =
lambda do |h|
Hash === h ?
Hash[
h.map do |k, v|
[k.respond_to?(:to_sym) ? k.to_sym : k, s2s[v]]
end
] : h
end
s2s[hash] #=> {:d=>"e", #<Object:0x100396ee8>=>"g", :a=>{:b=>"c"}}