如何转换Ruby哈希以使其所有键都是符号? [英] How do I convert a Ruby hash so that all of its keys are symbols?

查看:97
本文介绍了如何转换Ruby哈希以使其所有键都是符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {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太短:没有看到递归一词,但是如果你坚持(同时保护不存在 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}}


I have a Ruby hash which looks like:

{ "id" => "123", "name" => "test" }

I would like to convert it to:

{ :id => "123", :name => "test" }

解决方案

hash = {"apple" => "banana", "coconut" => "domino"}
Hash[hash.map{ |k, v| [k.to_sym, v] }]
#=> {:apple=>"banana", :coconut=>"domino"}

Update:

@mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent 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"}}

这篇关于如何转换Ruby哈希以使其所有键都是符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆