All posts

Convert ruby hash with string keys to symbol keys

 ruby

If you have a ruby hash with string / arrow keys like so:

{
  "key1" => "val1",
  "key2" => "val2"
}

But you want the hash to have symbol keys, you can use the transform_keys method:

{
  "key1" => "val1",
  "key2" => "val2"
}.transform_keys(&:to_sym)

=> {:key1=>"val1", :key2=>"val2"}

Further reading:

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).