Search code examples
rubyhashstringify

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

Solution

  • 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