From: Gavin Kistner Date: 2005-09-14T21:36:51+09:00 Subject: Re: Assigning to dynamic class attributes On Sep 13, 2005, at 2:36 PM, daz wrote: > Allen wrote: >> Also, I don't completely understand how symbols work or >> why they are needed. > > If you use strings to identify fields, each time you write the > field name, a new string is created. Symbols are unique and > memory-efficient. > > p 'cremote'.object_id #-> 23356052 > p 'cremote'.object_id #-> 23356016 > p 'cremote'.object_id #-> 23355992 > puts > p :@cremote.object_id #-> 3504654 > p :@cremote.object_id #-> 3504654 > p :@cremote.object_id #-> 3504654 While :@cremote is a valid symbol, it sort of implies that the @ symbol is somewhow special for symbols. The corresponding symbol to "cremote" is :cremote. irb(main):001:0> a = 'cremote' => "cremote" irb(main):002:0> a.to_sym => :cremote irb(main):003:0> a.to_sym.to_s => "cremote" Note also that symbols are immutable (like a large integer), while strings are mutable (like an Array). Think of symbols as a unique identifier that you can pass around in a lightweight and unambiguous way. For example, symbols are often used for the value of constants: class Person MALE = :male FEMALE = :female attr_reader :sex def initialize( sex ) @sex = sex end end pat = Person.new( Person::MALE ) jim = Person.new( Person::MALE ) if jim.sex == Person::FEMALE # This won't occur raise "Something went bad!" end Compare to this pathological case: class Person MALE = 'male' FEMALE = 'female' attr_reader :sex def initialize( sex ) @sex = sex end end pat = Person.new( Person::MALE ) jim = Person.new( Person::MALE ) # Trying to give JUST pat a sex change, the wrong way pat.sex.sub!( /^/, 'fe' ) if jim.sex == Person::FEMALE # This will occur! raise "Something went bad!" end