Why are symbols not frozen strings?

前端 未结 6 1915
广开言路
广开言路 2021-01-31 17:59

I understand the theoretical difference between Strings and Symbols. I understand that Symbols are meant to represent a concept or a name or an identifier or a label or a key, a

6条回答
  •  孤街浪徒
    2021-01-31 18:26

    This answer drastically different from my original answer, but I ran into a couple interesting threads on the Ruby mailing list. (Both good reads)

    So, at one point in 2006, matz implemented the Symbol class as Symbol < String. Then the Symbol class was stripped down to remove any mutability. So a Symbol was in fact a immutable String.

    However, it was reverted. The reason given was

    Even though it is highly against DuckTyping, people tend to use case on classes, and Symbol < String often cause serious problems.

    So the answer to your question is still: a Symbol is like a String, but it isn't.
    The problem isn't that a Symbol shouldn't be String, but instead that it historically wasn't.

提交回复
热议问题