How to create Hash with string keys by default

Joerg picture Joerg · Oct 21, 2016 · Viewed 13.9k times · Source

When I do the following:

h = { "a": 123 }

Ruby converts the key to a symbol automatically.

h[:a]  # => 123
h["a"] # => nil

How can I prevent this behaviour? I created the hash with a string key, and would like to keep it that way without always having to call Hash#stringify_keys.

Answer

Andrey Deineko picture Andrey Deineko · Oct 21, 2016

Use hash rocket syntax:

h = { "a" => 123 }
#=> {"a"=>123}
h['a']
#=> 123