From: Simen Date: 2006-03-26T21:34:23+09:00 Subject: Re: deciphering poignant guide chapter 4 example unknown wrote: > The poinant guide says it's just "words that look just like > variables". And "Symbols are lightweight strings." But that > doesn't help me much. The PickAxe 2nd ed, in chapter 3 says, > "The construct :artist is an expression that returns a Symbol > object corresponding to artist.", so, I can understand that > (i.e. that there's some Symbol class and we're getting an > instance of it by using that notation), but I'm still not > getting the point... why not just use strings? What does > having "Symbols" buy the programmer? Symbols are not merely lightweight strings, they represent names in the Ruby interpreter. Check this sample out to see the difference: $ irb irb(main):001:0> "Hello".object_id => -605430718 irb(main):002:0> "Hello".object_id => -605437098 irb(main):003:0> :hello.object_id => 3985678 irb(main):004:0> :hello.object_id => 3985678 irb(main):005:0> :hello.object_id == :hello.object_id => true irb(main):006:0> "hello".object_id == "hello".object_id => false irb(main):007:0> Symbols with the same values are the same objects, that is not the case with strings. Symbols represents identifiers, strings values. For example def method_missing( id, *args ) puts id.class end asdf # undefined method Would output "Symbol", since the method identifier is indeed an identifier. Symbols are simply names of stuff. Use them when you need to name something whose value may change, but not whose semantics (ie ary[:greeting] may be "Hello world" or "Hello johnny" but it's allways a greeting. You shouldn't use Symbols for stuff you're going to output to some io, for example, there's no point in doing puts :"Hello world" instead of puts "Hello world" (Maybe some Ruby gurus could explain this better than me). -- Posted via http://www.ruby-forum.com/.