tags:

views:

122

answers:

3

I was just wondering why Ruby exposes symbols for explicit use - isn't that the sort of optimisation that's usually handled by the interpreter / compiler? Thanks for any insight :)

+6  A: 

Part of the issue is that Ruby strings are mutable. Since every string Ruby allocates must be independent (it can't cache short/common ones), it's convenient to have a Symbol type to let the programmer have what are essentially immutable, memory-efficient strings.

Also, they share many characteristics with enum's, but with less pain for the programmer.

zenazn
Thanks zenzan, I get it now. I think I'd already got a reasonable-ish handle on the how and why of symbols in Ruby, but as you say it's the mutability, strings as a first class object that makes the difference. So things that looks like literals aren't really and can't be treated as such by the interpreter.
Jerome
+3  A: 

Ruby symbols are used in lieu of string constants in other similar languages. Besides the performance benefit, they can be used to semantically distinguish between string data and a more abstract symbol. Being syntactically different, they can clearly be distinguished in code.

troelskn
Thanks troelskn, yes I guess the nuance of symbol vs 'literal' is helpful when reading the code.
Jerome
+1  A: 

Have a look at Ruby symbols post.

khelll
Nice article, thanks khelll
Jerome
You may also want to look at http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol
Andrew Grimm