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

后端 未结 3 1663
不思量自难忘°
不思量自难忘° 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条回答
  •  难免孤独
    2021-02-02 07:49

    It's because of the new hash syntax introduced with ruby 1.9. The syntax with colon works with symbol keys only. It's called a "symbol to object" hash and it's only syntactic sugar for the most common style of hashes out there. Another point for me, it's closer to the javascript object notation.

    If I have mixed key types then I prefer the old style (hash-rocket syntax), but that's up to you. Mixing the two style looks ugly to me.

提交回复
热议问题