|
Symbols in Ruby are very much like strings, except a symbol takes only one memory address, no matter how many times you use it(no matter how many instances of it you have in your program).
Each instance of a string takes a different memory address.
The first advantage of using symbols has that we can draw from the things mentioned above, is that using symbols as often as possible instead of strings helps us save memory space.Symbols are used especially when defining Hashes (discussed in a further chaper)
Symbols are global read-only objects, you cannot alter the value of a symbol as you can do with strings.
You access a symbol using the ":[nameofsymbol]" syntax such as ":birthday".Ruby would look for the object associated with ":birthday" and it would return the exact same value every time an instance of the symbol is used.
A symbol can be easily converted to a string or integer by:
:testsymb.to_s
:testsymb.to_i
where "testsymb" represents the name of the symbol in cause.
You can also convert a string directly to a symbol like this:
x = "abracadabra"
y = :magicword
y == x.to_sym
A symbol is an instance of the Symbol class.A symbol has also been referenced as "an object that has a name".
It can be anything you want, not necessarily made up from just one word.
For example:
mysymbol1=:"this is good coffee"
mysymbol2=:"thanks"
mysymbol3=:"^ l33t ^"
...all of the above can be considered valid symbols.
The most 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")
There isn't much to say about symbols anyway so we will stop here for the moment.On with the next chapter...
|