I have just started using Ruby and I am reading "Programming Ruby 1.9 - The Pragmatic Programmer's Guide". I came across something called symbols, but as a PHP developer I don't understand what they do and what they are good for.
Can anyone help me out with this?
Symbols are similar to string literals in the sense that share the same memory space, but it is important to remark they are not string equivalents.
In Ruby, when you type
"this"
and"this"
you're using two different memory locations; by using symbols you'll use only one name during the program execution. So if you type:this
in several places in your program, you'll be using only one.From Symbol doc:
So, you basically use it where you want to treat a string as a constant.
For instance, it is very common to use it with the
attr_accessor
method, to define getter/setter for an attribute.But this would do the same:
It's useful to think of symbols in terms of "the thing called." In other words, :banana is referring to "the thing called banana." They're used extensively in Ruby, mostly as Hash (associative array) keys.
They really are similar to strings, but behind the scenes, very different. One key difference is that only one of a particular symbol exists in memory. So if you refer to :banana 10 times in your code, only one instance of :banana is created and they all refer to that one. This also implies they're immutable.
@AboutRuby has a good answer, using the terms "the thing called".
He notes that you can refer to :banana many times in the code and its the same object-- even in different scopes or off in some weird library. :banana is the thing called banana, whatever that might mean when you use it.
They are used as
Think of a Symbol as a either:
For example: