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: , , ,

CSS Hackary »
« Ruby Language Goodies For Java Developers
 
Related Posts
Recent Posts
 

2 Comments so far

  1. Daniel B on January 10th, 2007

    Hi, thanks for that, I’ve been reading a lot of articles trying to understand how to define symbols, most say what symbols are good for, not how to define them. Thanks! :)

  2. TechKnow on January 12th, 2007

    No problem. I am glad you found this helpful!!!

Leave a reply