0

Possible Duplicate:
Understanding Symbols In Ruby
What is the colon operator in Ruby?

This is some code the Rails tutorial I'm reading gives me.

class Post < ActiveRecord::Base
  attr_accessible :content, :name, :title

  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
end

What do the :content, :name, and :title mean? I vaguely remember these from the ruby tutorial I was reading (hlrb), but I can't find them when I'm skimming through it. What do these words prefixed by a colon mean?

Community
  • 1
  • 1
Orcris
  • 2,695
  • 6
  • 22
  • 24

1 Answers1

9

The words your referring to are called symbols.

What are symbols you ask? They are more or less like strings, except they are immutable (can't be changed) and are singletons (are only ever created once in memory, no matter how many times you use them).

That means that they get used as keys everywhere, because they are more memory efficient.

So if you have two hashes, for instance, and have a key called key, using a string for the hash key:

my_hash['key'] #in memory once
your_hash['key'] # in memory twice

If you use a symbol

my_hash[:key] # in memory once
your_hash[:key] # still in memory once!

You may also encounter symbols in this form:

key: 'value'

This is the same as

:key => 'value'
DVG
  • 17,144
  • 7
  • 58
  • 82