Monday, March 19, 2007

Symbol in Ruby on Rails

Symbols are instances of the built-in Ruby class Symbol. They have a literal constructor: the leading colon.
:book, :"Here's how to make a symbol with spaces in it."
You can also create a symbol programmatically, by calling the to_sym method or intern method on a string, as irb shows:
$ "a".to_sym
$ :a

Indeed, symbols are very closely related strings. They share responsibility for representing units of text. However, strings and symbols differ in some important ways:
1, Every time you see the notation for a particularsymbol (:a), you’re seeing the same symbol object represented. If you see two identical-looking string literals"a""a" you’re seeing two different string objects.
2, Symbols,unlike strings, are immutable; you cannot add, remove, or change parts of a symbol. 就是说symbol是不可改变的,而string是可以改变内容的。

It’s worth knowing that symbols are efficient in terms of memory usage and processing time. Strings, on the other hand, come with an entourage of behaviors and capabilities that makes them more expensive to maintain and process (like being made longer than they started out, having their contents changed, and so on).

Using symbols in Rails

You’ll often see symbol literals used as arguments to methods and, especially, as hash keys. Hashes that serve as arguments to methods are a doubly likely candidate for symbol usage.

In the case of method calls in Rails applications, a consensus exists on the syntax of method calls whose arguments are symbols. Using symbol literals is second nature in Rails development.
<%= link_to "Click here", :controller => "book", :action => "show", :id => book.id %>
This is an example of a method argument hash: Each of the symbols is a key, and each of the values to the right is a value. This style of method call is common in Rails application code.

No comments: