Tuesday, May 15, 2012

What is a ruby symbol?

Basically, a ruby symbol is an identifier that can't be changed. It's supposed to be, from my understanding, sort of a placeholder.


For example, say you have a bunch of hashes (dictionaries/hashtables). And they all have the same keys, but different values. Storing each key as a string would take up a ton of memory. Instead, you can store it as a symbol. With a symbol, each instance points to the same thing in memory.


To define a symbol, for example to store the name of something in a hash table, you type :name. You CANNOT say :name = 'john', because you can't "set" symbols to other things. Instead, you can define a hash or something like this: h = {:name => 'john', :occupation => 'carpenter'}.


Here, you are defining a representation of john the carpenter. You could have used strings as the keys in that hash table, but that's not really what strings are meant to be used for in ruby (as opposed to in python, where strings are immutable). You use the symbol as a placeholder, because it's easier and more conventional. Also, if you have 1,000 hashes to represent 1,000 people, using symbols will save you a pretty good chunk of memory.


You can get a string representation of the symbol if you need to with :name.to_s, but that doesn't make a lot of sense with a symbol. Basically, it seems to me that ruby symbols are a convenient way to enforce, or at least push people towards, a better convention for defining keys. Really, a symbol is a key, that you use to access something else.


That's what a ruby symbol is.

No comments:

Post a Comment