Leigh  McCulloch
Leigh McCulloch

Reputation: 1976

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

Upvotes: 2

Views: 1796

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110675

{ id: 123, name: "test" }.transform_keys(&:to_s)
  #=> {"id"=>123, "name"=>"test"}

See Hash#transform_keys.

Upvotes: 4

Ajedi32
Ajedi32

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

Arup Rakshit
Arup Rakshit

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

Leigh  McCulloch
Leigh McCulloch

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

Related Questions