Ruby Symbols

If you are new to the Ruby programming language and only just recently started programming in Ruby via Rails you must be wondering what the hell are those thingies used to name actions in the link_to ActionView helper function. Here is an an example of what I mean:

<%= link_to 'link', :action => 'myaction' %>

The :action is a instance of a Symbol. In rails symbols are used as string in many places. For example, instead of providing a string for the name of the action I could have used a symbol:

<%= link_to 'link', :action => :myaction %>

There are a few additional ways to create symbols. You can create the myaction symbol in any of the following ways.

<%= link_to 'link', :action => :'myaction' %>
<% myvar = 'myaction' %>
<%= link_to 'link', :action => :"#{myvar}" %>
<%= link_to 'link', :action => myvar.intern %>
<%= link_to 'link', :action => "myaction".to_sym %>

It is good to remember that symbols are immutable and that the system will only hold onto one copy of a symbol no matter how many times you create references to them.

Technorati Tags: , , ,

Related posts:

  1. Ruby On Rails Controller Path
  2. Calendar Helper Plugin
  3. Rails Named Routes
  4. Creating Custom Rails Routes
  5. Rad Ruby On Rails
  6. Ruby On Flex


3 Responses to “Ruby Symbols”

Leave a Reply