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

Enjoy. Share. Be Happy.
  • Twitter
  • Facebook
  • StumbleUpon
  • del.icio.us
  • Tumblr
  • Google Bookmarks
  • FriendFeed
  • Yahoo! Buzz
  • Reddit
  • Digg
  • HackerNews
  • Suggest to Techmeme via Twitter
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • Mixx
  • Furl

Related posts:

  1. Ruby On Rails Controller Path
  2. Rails Named Routes
  3. Calendar Helper Plugin
  4. Creating Custom Rails Routes
  5. Ruby Class Tutorial

This entry was posted in Ruby, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Daniel B
    Posted January 10, 2007 at 4:49 am | Permalink

    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. Posted January 12, 2007 at 1:12 am | Permalink

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

One Trackback

  1. By Ruby Class Tutorial on July 20, 2009 at 2:31 pm

    [...] the Person class using the attr_accessor method, which dynamically defines accessor methods for the symbol [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*