在哈希火箭之前用冒号替换双引号

时间:2016-02-01 03:44:07

标签: ruby regex

我有以下哈希:

{"_id"=>BSON::ObjectId('567ccbd747824a621d8b4567'), "response"=>{"version"=>"1.1", "statusCode"=>302, "headers"=>{"content-type"=>[""], "content-length"=>[""], "host"=>["54.223.52.194:9011"], "connection"=>["keep-alive"], "cache-control"=>["max-age=0"], "accept"=>["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], "upgrade-insecure-requests"=>["1"], "user-agent"=>["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36"], "accept-encoding"=>["gzip, deflate, sdch"], .......}

我想用冒号替换双引号。预期的输出是:

{:_id=>BSON::ObjectId('567ccbd747824a621d8b4567'), :response=>{:version=>"1.1",.....}

我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用符号键构建一个新哈希:

def symbolize_keys(o)
   case o
   when Hash
     Hash[o.map { |k, v| [k.to_sym, symbolize_keys(v)] }]
   when Array
     o.map { |e| symbolize_keys(e) }
   else
     o
   end
end

(假设你的意思是“冒号”而不是“逗号”)

答案 1 :(得分:2)

只需将所有密钥映射到Symbol s:

hsh.map {|k, v| [k.to_sym, v] }.to_h