Reputation: 1976
I have a ruby hash which looks like:
{ id: 123, name: "test" }
I would like to convert it to:
{ "id" => 123, "name" => "test" }
Upvotes: 2
Views: 1796
Reputation: 110675
{ id: 123, name: "test" }.transform_keys(&:to_s)
#=> {"id"=>123, "name"=>"test"}
See Hash#transform_keys.
Upvotes: 4
Reputation: 48368
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
Upvotes: 3
Reputation: 118271
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" }
Upvotes: 4
Reputation: 1976
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" }
Upvotes: 5