Why are symbols not frozen strings?

Posted by Alex Chaffee on Stack Overflow See other posts from Stack Overflow or by Alex Chaffee
Published on 2012-06-18T15:01:39Z Indexed on 2012/06/18 15:16 UTC
Read the original article Hit count: 243

Filed under:
|

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, and Strings are a bag of characters. I understand that Strings are mutable and transient, where Symbols are immutable and permanent. I even like how Symbols look different from Strings in my text editor.

What bothers me is that practically speaking, Symbols are so similar to Strings that the fact that they're not implemented as Strings causes a lot of headaches. They don't even support duck-typing or implicit coercion, unlike the other famous "the same but different" couple, Float and Fixnum.

The mere existence of HashWithIndifferentAccess, and its rampant use in Rails and other frameworks, demonstrates that there's a problem here, an itch that needs to be scratched.

Can anyone tell me a practical reason why Symbols should not be frozen Strings? Other than "because that's how it's always been done" (historical) or "because symbols are not strings" (begging the question).

Consider the following astonishing behavior:

:apple == "apple"  #=> false, should be true

:apple.hash == "apple".hash #=> false, should be true

{apples: 10}["apples"]  #=> nil, should be 10

{"apples" => 10}[:apples]  #=> nil, should be 10

:apple.object_id == "apple".object_id #=> false, but that's actually fine

All it would take to make the next generation of Rubyists less confused is this:

class Symbol < String
  def initialize *args
    super
    self.freeze
  end

(and a lot of other library-level hacking, but still, not too complicated)

See also:

© Stack Overflow or respective owner

Related posts about ruby

Related posts about symbols