How to create a default hash with string keys

When I do the following:

h = { "a": 123 }

Ruby / Rails automatically converts the key to a character.

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

How can I prevent this behavior? I created a hash with a string key and would like to save it that way without naming it Hash#stringify_keys.

+4
source share
4 answers

Use rocket hash syntax:

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

Try

h = { "a" => 123 }

Colon will make your key a symbol.

+1
source

hashrocket :

h = { "a" => 123 }
#=> {"a"=>123}
+1

:

/,

. . :

:'foo-bar'.class # => Symbol

, , .

, " :foo / bar". , String#to_sym. , :

{'foo-bar'.to_sym => 42, :this_now_needs_rocket_notation => 'baz'}

, " " / -. , , , .

+1

Source: https://habr.com/ru/post/1658414/


All Articles