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

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

问题描述

我有一个 Ruby 哈希,它看起来像:

I have a Ruby hash which looks like:

{ "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"}

@mu 太短:没有看到递归"这个词,但如果你坚持(以及防止不存在的to_sym,只是想提醒一下,在 Ruby 1.8 1.to_sym == nil,因此使用某些键类型可能会产生误导):

@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天全站免登陆