Why are symbols not frozen strings?
- by Alex Chaffee
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:
http://onestepback.org/index.cgi/Tech/Ruby/SymbolsAreNotImmutableStrings.red
http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol
Why does my code break when using a hash symbol, instead of a hash string?
Why use symbols as hash keys in Ruby?
What are symbols and how do we use them?
Ruby Symbols vs Strings in Hashes
Can't get the hang of symbols in Ruby