Search code examples
ruby-on-railsrubystringsyntaxsymbols

How to create Hash with string keys by default


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.


Solution

  • Use hash rocket syntax:

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