Symbol is greatly used in Ruby programs. It is an object of Symbol class. It represents some strings inside the Ruby interpreter. When you think that the string you are going to create would probably going to be reused somewhere again, then you should consider using symbols. The benefit of Symbol is really performance. During a Ruby program’s execution, as long as the symbol contents are the same, they are actually the same object, so it will refer to the same object in memory. e.g.
user1 = {:name => "Shanison"}
user2 = {:name => "Lin"}
Above codes actually only creates 1 symbol object, 2 strings object and 2 hash objects. Imagine that you are creating a lot of hash, the :name symbol would save a lot of object creation. You can even query all the symbols in your program:
Symbol.all_symbols # return an array of symbols
Enough about the introduction to symbols. What I want to talk about is actually about Hash. When constructing a hash, you would use symbol as the keys quite often. Probably due to this reason, in Ruby 1.9 it introduced a new Syntax for Hash.
user1 = {name: "Shanison"}
user2 = {name: "Lin"}
At first glance, this looks pretty much like syntax for defining javascript object. Looks great. However, take note that the colon must be right after the key without any space. So it is not exactly the same as javascript object syntax.
user1 = {name : "Shanison"} # This will cause syntax error
This shorten syntax sometimes looks short and sweet when you pass it as a parameters.
server = Server.new( addr: "192.167.123.1", user: 'id_' ) # Compares to Below server = Server.new( :addr => "192.167.123.1", :user => 'id_' )
However, do note that this syntax only works for symbol keys. So if you want to use strings or numbers as the hash keys, you can’t write the syntax in this way. e.g. Below code would return you error:
user1 = {"name": "Shanison"} # Give Syntax error
user2 = {1: "Lin"} # Give Syntax error
You can even mix the syntax when your hash has both symbol and numbers as keys, although the combination looks funny.
user1 = {name: "Shanison", 1 => "one"}
However, when your value is also a symbol, this syntax looks really funny:
user1 = {name: :source}
Due to above reasons, I still prefer the old syntax. It is just an options and personal preference, so there is no right or wrong in which syntax you adopt.







