Symbols

A typical implementation of a Ruby interpreter maintains a symbol table in which it stores the names of all the classes, methods, and variables it knows about. This allows such an interpreter to avoid most string comparisons: it refers to method names (for example) by their position in this symbol table. This turns a relatively expensive string operation into a relatively cheap integer operation.

These symbols are not purely internal to the interpreter; they can also be used by Ruby programs. A Symbol object refers to a symbol. A symbol literal is written by prefixing an identifier or string with a colon:

:symbol                   # A Symbol literal
:"symbol"                 # The same literal
:'another long symbol'    # Quotes are useful for symbols with spaces
s = "string"
sym = :"#{s}"             # The Symbol :string

Symbols also have a %s literal syntax that allows arbitrary delimiters in the same way that %q and %Q can be used for string literals:

%s["]     # Same as :'"'

Symbols are often used to refer to method names in reflective code. For example, suppose we want to know if some object has an each method:

o.respond_to? :each

Here’s another example. It tests whether a given object responds to a specified method, and, if so, invokes that method:

name = :size
if o.respond_to? name
  o.send(name)
end

You can convert a String to a Symbol using the intern or to_sym methods. And you can convert a Symbol back into a String with the to_s method or its alias id2name:

str = "string"     # Begin with a string
sym = str.intern   # Convert to a symbol
sym = str.to_sym   # Another way to do the same thing
str = sym.to_s     # Convert back to a string
str = sym.id2name  # Another way to do it

Two strings may hold the same content and yet be completely distinct objects. This is never the case with symbols. Two strings with the same content will both convert to exactly the same Symbol object. Two distinct Symbol objects will always have different content.

Whenever you write code that uses strings not for their textual content but as a kind of unique identifier, consider using symbols instead. Rather than writing a method that expects an argument to be either the string “AM” or “PM”, for example, you could write it to expect the symbol :AM or the symbol :PM. Comparing two Symbol objects for equality is much faster than comparing two strings for equality. For this reason, symbols are generally preferred to strings as hash keys.

In Ruby 1.9, the Symbol class defines a number of String methods, such as length, size, the comparison operators, and even the [] and =~ operators. This makes symbols somewhat interchangeable with strings and allows their use as a kind of immutable (and not garbage-collected) string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.199