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
2010-02-21 20:46:03
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
2010-02-21 22:43:37
+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
2010-02-21 20:46:27
Thanks troelskn, yes I guess the nuance of symbol vs 'literal' is helpful when reading the code.
Jerome
2010-02-21 22:47:43
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
2010-02-23 22:22:08