1

I have a ruby hash which looks like:

{ id: 123, name: "test" }

I would like to convert it to:

{ "id" => 123, "name" => "test" }
Leigh McCulloch
  • 1,886
  • 24
  • 23

4 Answers4

5

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" }
Leigh McCulloch
  • 1,886
  • 24
  • 23
4

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" }
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
3

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
Ajedi32
  • 45,670
  • 22
  • 127
  • 172
3
{ id: 123, name: "test" }.transform_keys(&:to_s)
  #=> {"id"=>123, "name"=>"test"}

See Hash#transform_keys.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • I cheated. `transform_keys` was introduced in Ruby version 2.5, which did not appear until well after this question was posted. – Cary Swoveland Jan 03 '23 at 22:41