|
Symbols should also be used whenever you want to use strings as unique identifiers rather than their textual content. For instance, you can use symbols to represent different colors in a program.
colors = [:Red, :Green, :Blue]
Symbols are extremely useful as Hash keys. Again, quick lookup and a single copy. Hash keys respond to the hash method by returning a hash code which is then used as an index into the underlying hash table. It is crucial that the hash code for a given key not change or bad evil things happen. If the contents of the key change, thus changing its hash code, the hash lookup based on that key will fail to work as advertised. You may be thinking that using String objects has hash keys is bad but here is a little secret. If you use a String as a hash key, the Hash object will create an internal copy of they String key, freeze it and then use it as a key. But still, you don't get the advantage of a single copy.
Yet another common use of symbols in Ruby is for defining attributes on a class such as this for example:
class Programming
attr_accessor :language
def initialize(language)
@language = language
end
end
favorite = Programming.new("Ruby")
Last but not least, Ruby on Rails uses Symbol objects extensively. After all, Ruby on Rails is mostly metaprogramming black magic.
Some Symbol manipulation
A String can be converted to a Symbol using the intern or to_sym methods. You can convert a Symbol back into a string with the to_s method or its id2name alias.
s = "hello" # We start with a string
sym = s.intern # Let's get a symbol
sym = s.to_sym # And again
s = sym.to_s # Back to string
s = sym.id2name # Yet another way to do it
where "testsymb" represents the name of the symbol in cause.
Symbols can also be created using string substitution as shown below.
s = "hell"
:"#{s}fire" # we get the symbol :hellfire
That's all folks. On with the next chapter...
|