From: Robert Dober Date: 2007-08-14T18:11:04+09:00 Subject: Re: Symbols and strings On 8/14/07, maghac wrote: > Hi, > as a long-term perl user just recently converted to ruby, I'm curious > about one particular syntax "feature": ruby symbols and how they > relate to strings. > > Isn't really :name a shortcut for "name"? (I read somewhere in an > explanation of attr_reader that e.g :age was the "name" of the > variable age, while age is the actual content of that variable). If > so, couldn't you use this in hash keys as well, e.g say hashvar[:key] > instead of hashvar['key']. > > Are there situations where you cannot use symbols instead of strings, > or the other way around? > > I might be too used to the way strings and barewords are handled in > perl (if something looks like a string, and it's not a function call, > it's interpreted as a string. This means you can say $hashvar{key} > without quoting the key). This question is asked very frequently, please search the archives for more info. I will try to give a very quick answer nevertheless: Symbols are immutable, thus great to represent immutable data, often that makes them an excellent choice for hash keys { :the_value => 42, :alternatively => 22, :or_even => 101010 } they just do not play the role of Strings, coming from Perl you just had to use Strings, you did not have a tool for names (wait a moment was there not such a thing as references to constants?). Very roughly put I see Symbols as name, and Strings as data, whenever I can use Symbols I use them, comes natural after some time. HTH Robert -- [...] as simple as possible, but no simpler. -- Attributed to Albert Einstein