From: Eric Kidd Date: 2006-03-28T02:04:38+09:00 Subject: Re: deciphering poignant guide chapter 4 example On Mar 26, 2006, at 5:43 PM, john_sips_tea@yahoo.com wrote: >> As you seem to come from the Python's world, you probably >> know that Python's strings are immutable. And if you read a >> little bit about why strings in Python are immutable, you will >> see it's because they wanted to optimize the method lookup. > > I'll have to think about that. I don't see the connection between > strings and method lookup. Symbols and strings have various tradeoffs: 1) Comparing two strings may require looking at every character in each string. This means some kind of loop, which takes time. On the plus side, you can change the contents of a Ruby string. 2) Comparing two symbols takes only one instruction, because symbols are stored as pointers to objects. Every time you write ":foo", you get a pointer to the exact same ":foo" object. But since this object is shared (and represents a constant), you're not allowed to change it. The Ruby interpreter makes extensive use of symbols internally, for performance reasons. When should you use symbols? Mostly when you need some way to talk about the (computer's) "names" for things, and compare those names very efficiently. This generally occurs when implementing computer languages, or when trying to parse natural languages. How would you implement symbols? Usually with a hash table: # Pseudocode. This function would be called by the parser. def get_symbol_for_string(str) if hash contains object for str: return the object else make a new object, store it in the hash, and return it Cheers, Eric