Ruby has at least a couple of different ways of referencing variables. Class instance variables can be created with the @ prefix, like @my_var = "test", there's also an @@ prefix for class-level variables.
For the first few days I was learning Ruby and Ruby on Rails, I kept stumbling upon "variables" like :name. But when I tried to assign one, I quickly discovered that it wasn't a variable -- it was a symbol. My attempt resulted in a failure:
irb(main):001:0> :test = 4 SyntaxError: compile error (irb):1: syntax error, unexpected '=', expecting $end :test = 4 ^ from (irb):1
The ruby compiler didn't expect anything after the '=', and it complains.
What are Symbols?
According to the Symbol documentation:
Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program's execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.
A symbol acts as an alias to a name such as a variable, class, or method. As a simple example, consider the following two hashes:
u1 = { "name" => "Kaleb", "phone" => "private" } u2 = { "name" => "Larry", "phone" => "private" }
And here's a similarly structured hash using symbols:
u1 = { :name => "Kaleb", :phone => "private" } u2 = { :name => "Larry", :phone => "private" }
For each hash the compiler keeps copies of the keys "name" and "phone". For a couple of values this doesn't matter, but for thousands of records it adds up to a lot of duplication and wasted memory. A post on glu.ttono.us provides more concrete details on both symbols and memory usage differences.
No comments:
Post a Comment