Hacker News new | past | comments | ask | show | jobs | submit login

Personally, I found Ruby's symbols to be a source of bugs because they can easily get mixed up with strings. The article gives the example of dict[:employee_id]. But what happens if you serialize "dict" as JSON, then parse it again? The symbol :employee_id will be silently converted to "employee_id", which is treated as a different dict key from :employee_id. I found it was easy to lose track of whether a given dictionary is using the "keys are symbols" or the "keys are strings" convention, especially in larger codebases.



Yeah symbols are terrible and they lead to using Mashes or "Hashes with indifferent access" to attempt to allow both syntax. This helps with round tripping to JSON and back and getting consistent access either way, but values are still not converted. And values shouldn't be symbolized from JSON which means round tripping through JSON typically converts symbols into strings.

It would be a lot easier if symbols had been just syntactic sugar for immutable frozen strings so that :foo == "foo".freeze == "foo" would be true.

And under the covers these days there is very little difference. It used to be that symbols were immutable and not garbage collected and fast. And that strings were mutable and garbage collected and slow.

These days symbols are immutable and garbage collected and fast and frozen strings are immutable and garbage collected and fast (and short mutable strings are even pretty fast).

Symbols as a totally different universe from Strings I would consider to be an antipattern in language design. They should just be syntactic sugar for frozen strings if your language doesn't already have frozen strings by default.


Always serialize the keys back to symbols.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: