2016-02-01 74 views
-2

前更換結腸癌雙引號我有如下哈希:哈希火箭

{"_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",.....} 

我怎麼能這樣做?

+0

不完全相同:http://stackoverflow.com/a/4045194/2988 –

回答

3

建立一個新的Hash,具有象徵性的鑰匙:

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 

(假設你的意思是 「冒號」,而不是 「逗號」)

+0

謝謝!你保存我的一天 – roccia

1

所有的按鍵就映射到Symbol S:

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