简体   繁体   中英

How do I convert a Ruby hash so that all of its keys are strings

I have a ruby hash which looks like:

{ id: 123, name: "test" }

I would like to convert it to:

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

I love each_with_object in this case :

hash = { id: 123, name: "test" }
hash.each_with_object({}) { |(key, value), h| h[key.to_s] = value }
#=> { "id" => 123, "name" => "test" }

If you are using Rails or ActiveSupport:

hash = { id: 123, description: "desc" }
hash.stringify #=> { "id" => 123, "name" => "test" }

If you are not:

hash = { id: 123, name: "test" }
Hash[hash.map { |key, value| [key.to_s, value] }] #=> { "id" => 123, "name" => "test" }

In pure Ruby (without Rails), you can do this with a combination of Enumerable#map and Array#to_h :

hash = { id: 123, name: "test" }
hash.map{|key, v| [key.to_s, v] }.to_h
h = { id: 123, name: "test" }

Assuming you want to mutate h :

h.keys.each { |k| h[k.to_s] = h.delete(k) }
h #=> {"id"=>123, "name"=>"test"}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM