On Mon, May 25, 2009 at 1:56 PM, Bertram S.
=> [ … (loads)]
:phone.methods == Symbol.instance_methods
Strings are mutable, Symbols are immutable.
There is only one instance of a Symbol with a given string ‘value’ so
(hash1 == hash2) iff (hash1.object_id == hash2.object_id)
This is the main property of a Symbol, it’s used for keys in Hashes
where lookup performance is important (like the method hashes used
internally by Ruby), since it means that Hash#== is O(1) and doesn’t
depend on the ‘length’
The downside is that Symbols can’t be garbage collected (at least for
the MRI implementation) in order to preserve the id/value invariant a
list of all string values which have been ‘interned’ when a Hash has
been created needs to be kept.
In Rails, it’s common to see Symbol and String keys used
‘interchangeably’, but this is only possible because Rails provides a
HashWithIndifferentAccess class which actually uses string keys
internally (because of the GC issue) but allows either to be used as
key arguments to methods.