Why is this string key in a hash converted to a symbol?

后端 未结 3 1660
不思量自难忘°
不思量自难忘° 2021-02-02 07:16

Using Ruby 2.3:

In example 1, the string key \"a\" is automatically converted to a symbol, whereas with example 2, it stays a string.

Example 1

3条回答
  •  梦毁少年i
    2021-02-02 07:23

    According to Ruby documentation:

    Blockquote Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. [...]

    This means that running:

    $ ruby -e ruby -e "h = {key: \"value\"}; puts h"
    $ ruby -e ruby -e "h = {:key => \"value\"}; puts h"
    $ ruby -e ruby -e "h = {\"key\": \"value\"}; puts h"
    $ ruby -e ruby -e "h = {:\"key\" => \"value\"}; puts h"
    $ ruby -e ruby -e "h = {\"#{:key}\": \"value\"}; puts h"
    

    Will produce the same result:

    $ {:key=>"value"}
    

提交回复
热议问题