From: Rick DeNatale Date: 2009-05-26T03:13:01+09:00 Subject: Re: hash assignment [:x] vs ['x'] On Mon, May 25, 2009 at 1:56 PM, Bertram Scharpf wrote: > Hi, > > Am Dienstag, 26. Mai 2009, 02:19:29 +0900 schrieb Mk 27: >> bob['phone'] >> bob[:phone] >> >> That seems slightly weird, I had assumed the :form is just a shorthand >> like %w(  ).  So -- is there anything more that I need to understand >> about this distinction? > >  $ irb >  irb(main):001:0> :phone.class >  => Symbol >  irb(main):002:0> 'phone'.class >  => String > > and > >  irb(main):003:0> :phone.methods.sort - 'phone'.methods >  => ["id2name", "to_int"] >  irb(main):004:0> String.instance_methods.sort - Symbol.instance_methods >  => [ ... (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. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale